myBlog

IronPython, Silverlight, WPF, XAML, HTML5, ...

IronPythonで、XAMLから、ドックパネル( DockPanel )を表示

2011-07-06 17:11:52 | IronPython
今回は、シンプルなプログラムです。
IronPythonで、XAMLを使って、DockPanelを表示します。
普通のXAMLと、LastChildFill="False" を指定したXAMLです。

Blog: .NETな日々 ⇒ [WPF] WPF入門 ~レイアウト [DockPanel]~
http://blogs.wankuma.com/kzt/archive/2009/03/17/169777.aspx
を、参考にさせていただきました。[ .NETな日々 ]は良くできています。
サンプルが上手に使われていて、わかりやすいです。

#
# DockPanelTestFill.py

import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
from System import Object
from System.Windows import Window, Application
from System.Windows.Markup import XamlReader
xaml_str="""
<Window
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" Height="300" Width="300"> 
    <DockPanel> 
        <Button DockPanel.Dock="Left">Left</Button> 
        <Button DockPanel.Dock="Top">Top</Button> 
        <Button DockPanel.Dock="Right">Right</Button> 
        <Button DockPanel.Dock="Bottom">Bottom</Button> 
        <Button DockPanel.Dock="Top">Fill</Button> 
    </DockPanel> 
</Window>
"""
class ExWindow(Object):
    def __init__(self):
        self.Root = win = XamlReader.Parse(xaml_str)
if __name__ == "__main__":
    win = ExWindow()
    Application().Run(win.Root)

#
# DockPanelTestNotFill.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
from System import Object
from System.Windows import Window, Application
from System.Windows.Markup import XamlReader
xaml_str="""
<Window
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="Window1" Height="300" Width="300"> 
    <DockPanel LastChildFill="False" > 
        <Button DockPanel.Dock="Left">Left</Button> 
        <Button DockPanel.Dock="Top">Top</Button> 
        <Button DockPanel.Dock="Right">Right</Button> 
        <Button DockPanel.Dock="Bottom">Bottom</Button> 
        <Button DockPanel.Dock="Top">Not Fill</Button> 
    </DockPanel> 
</Window>
"""
class ExWindow(Object):
    def __init__(self):
        self.Root = win = XamlReader.Parse(xaml_str)
if __name__ == "__main__":
    win = ExWindow()
    Application().Run(win.Root)

IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、図形とブラシ( Shape, Brush )を動的に作成

2011-07-05 13:09:30 | IronPython
タブ・コントロール TabControl に、図形・ブラシを動的に作成
BLOG: 続・ひよ子のきもち
2008-10-13 第4章 ブラシ 1/5, LinearGradientBrush
http://d.hatena.ne.jp/kotsubu-chan/20081013
2008-05-12 第2章 TabControl 1/1
http://d.hatena.ne.jp/kotsubu-chan/20080512
等複数のページから、 XAMLとIronPythonのコード を myBlog 用に少しアレンジしています。

続・ひよ子のきもち は、本当に興味深いPageです。
WPF・IronPython・OOP について、色々と教えてもらいました。

Exbrush

#
# exBrush.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase') # for Point, Rect

from System import Object, Uri, UriKind
from System.Windows.Markup import XamlReader
from System.Windows import (
        Window, Application, Point, Rect, LogicalTreeHelper, Thickness)
#from System.Windows.Controls import Canvas
from System.Windows.Media import (
        Color, Colors, SolidColorBrush, Brushes, PointCollection, DrawingGroup, DrawingBrush, 
        VisualBrush, ImageBrush, LinearGradientBrush, RadialGradientBrush, GradientStop,
        GeometryGroup, RectangleGeometry,TileMode,EllipseGeometry, GeometryDrawing)
from System.Windows.Media.Imaging import BitmapImage
from System.Windows.Shapes import Ellipse, Polygon

xaml_str="""
<TabControl
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">

    <TabItem   Header="SolidColorBrush">
        <WrapPanel Name="solidColorBrush" />
    </TabItem>
    <TabItem   Header="LinearGradientBrush">
        <WrapPanel Name="linearGradientBrush" />
    </TabItem>
    <TabItem   Header="RadialGradientBrush">
        <WrapPanel Name="radialGradientBrush" />
    </TabItem>
    <TabItem   Header="ImageBrush">
        <WrapPanel Name="imageBrush" />
    </TabItem>
    <TabItem   Header="DrawingBrush">
        <WrapPanel Name="drawingBrush" />
    </TabItem>
    <TabItem   Header="VisualBrush">
        <WrapPanel Name="visualBrush" />
    </TabItem>
</TabControl>
"""
class ExWindow(Window):
    def __init__(self, Content=None, **args):
        for key,value in args.items():
            setattr(self,key,value)
        self.InitializeComponent(Content)
        self.init()

    def InitializeComponent(self, Content):
        self.Content = XamlReader.Parse(Content)
        
    def init(self):
        target = (
            "solidColorBrush",
            "linearGradientBrush",
            "radialGradientBrush",
            "imageBrush",
            "drawingBrush",
            "visualBrush",
            )
        self._Controls(target)

    def _Controls(self, target):
        for e in target:
            #c = LogicalTreeHelper.FindLogicalNode(self.Content, e)
            c = self.Content.FindName(e)
            setattr(self, e, c)
        for e in target:
            items = getattr(self, e)
            for shape in self.newEllipse(), self.newPolygon():
                shape.Fill = getattr(self, "_%s"%e)()
                items.Children.Add(shape)

    def _solidColorBrush(self):
        return Brushes.Yellow

    def _linearGradientBrush(self):
        brush = LinearGradientBrush()
        for color, offset in [
            ("Yellow", 0.0),    # follow me ..)^.^)
            ("Green" , 1.0),
            ]: 
            brush.GradientStops.Add(GradientStop(
                Color=getattr(Colors, color),
                Offset=offset,
                ))
        return brush

    def _radialGradientBrush(self):
        brush = RadialGradientBrush()
        for color, offset in [
            ("Yellow", 0.0),    # follow me ..)^.^)
            ("Green" , 1.0),
            ]: 
            brush.GradientStops.Add(GradientStop(
                Color=getattr(Colors, color),
                Offset=offset,
                ))
        return brush

    def _imageBrush(self):
        return ImageBrush(
            ImageSource = BitmapImage(Uri("http://softgarden.lovepop.jp/myBlog/image/j0182772.jpg")))
            #ImageSource= BitmapImage(Uri("j0182772.jpg", UriKind.Relative)))
    def _drawingBrush(self):
        brush = DrawingBrush(
            Viewport=Rect(0, 0, 0.1, 0.1),
            TileMode=TileMode.Tile,
            )
        sheet = GeometryDrawing(
            brush=Brushes.Yellow,
            pen=None,
            geometry=RectangleGeometry(Rect(0, 0, 50, 50)))
        geometry = GeometryGroup()
        for (px, py), rx, ry in (
            ((10, 10), 10, 10),
            ((35, 35), 15, 15),
            ):
            geometry.Children.Add(EllipseGeometry(
                Center=Point(px, py),
                RadiusX=rx,
                RadiusY=ry,
                ))
        marble = GeometryDrawing(
            brush=Brushes.Blue,
            pen=None,
            geometry=geometry)
        drawing = DrawingGroup()
        for e in sheet, marble:
            drawing.Children.Add(e)
        brush.Drawing = drawing
        return brush

    def _visualBrush(self):
        brush = VisualBrush()
        brush.Visual = self.imageBrush
        return brush

    def newEllipse(self):
        return Ellipse(
            Stroke=Brushes.Blue,
            StrokeThickness=2,
            Width=100,
            Height=50,
            )

    def newPolygon(self):
        points = PointCollection()
        vertices = "0,28 80,28 12,80 40,0 68,80"
        for e in vertices.split(" "):
            x, y = eval(e)
            points.Add(Point(x, y))
        return Polygon(
            Stroke=Brushes.Blue,
            StrokeThickness=2,
            Points=points,
            )

if __name__ == "__main__":
    win = ExWindow(Title="exBrush.py", Width=400, Height=200, Content=xaml_str)
    Application().Run(win)

IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、ColorListView を作りました

2011-07-05 03:50:48 | DataBinding
カラー・リストビュー ( ColorListView )を作ってみました。
BLOG: 続・ひよ子のきもち ==> ListView
http://d.hatena.ne.jp/kotsubu-chan/20090706
から、XAML と IronPython のコード を myBlog 用に少しアレンジしています。
XAMLのなかで、DataBinding が使われています。

続・ひよ子のきもち は、とても興味深いPageです。
WPF・IronPythonについて、色々と教えてもらいました。

Exlistview

#
# exListView.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase')
from System import Object
from System.Windows.Markup import XamlReader
from System.Windows import Window, Application
from System.Windows.Media import SolidColorBrush, Brushes
#from System.Windows.Controls import Grid
#from System.Windows.Data import Binding, BindingOperations
from System.Collections.ObjectModel import ObservableCollection

xaml_str="""
<DockPanel LastChildFill="True"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <ListView Name="listView" DockPanel.Dock="Left">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Color Name" 
                    DisplayMemberBinding="{Binding Path=name}"  Width="90" />
                <GridViewColumn Header="Red" 
                    DisplayMemberBinding="{Binding Path=red}"   Width="45" />
                <GridViewColumn Header="Green" 
                    DisplayMemberBinding="{Binding Path=green}" Width="45" />
                <GridViewColumn Header="Blue" 
                    DisplayMemberBinding="{Binding Path=blue}"  Width="45" />
            </GridView>
        </ListView.View>
    </ListView>
    <Canvas Name="colorBox" />
</DockPanel>
"""
class ColorItem:
    def __init__(self, name):
        e = getattr(Brushes, name).Color
        self.name  = name
        self.red   = e.R
        self.green = e.G
        self.blue  = e.B
    def __str__(self):
        return "'%s'(%d,%d,%d)"%(
            self.name, self.red, self.green, self.blue)

class ExWindow(Window):
    def __init__(self, Content=None, **args):
        for key,value in args.items():
            setattr(self, key, value)
        self.InitializeComponent(Content)
        self.init()
        
    def InitializeComponent(self, Content):
        self.Content = XamlReader.Parse(Content)
        
    def init(self):
        target = "listView", "colorBox"
        for e in target:
            control = self.Content.FindName(e)
            setattr(self, e, control)     
        self.listView.ItemsSource = ObservableCollection[Object]()
        for e in self.colorBrushes():
            self.listView.ItemsSource.Add(ColorItem(e))            
        self.listView.SelectionChanged += self.selectionChanged
        
    def colorBrushes(self):
        return [e for e in dir(Brushes)
            if isinstance(getattr(Brushes, e), SolidColorBrush)]
    
    def selectionChanged(self, sender, e):
        e = sender.SelectedItem
        print e
        self.colorBox.Background = getattr(Brushes, e.name)        

if __name__ == "__main__":
    win = ExWindow(Title="exListView", Width=380, Height=150, Content=xaml_str)
    Application().Run(win)


IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、System.Reflection を使って ColorComboBoxを作りました

2011-07-04 22:21:20 | Animation
BLOG: Nine Works ==> 色を選択するComboBoxの作り方
http://nine-works.blog.ocn.ne.jp/blog/2011/01/combobox_f98e.html
を参考にさせていただきました。
C# のプログラムを IronPython に変換しました。

前回のカラー・コンボボックスは、Python の dir(Colors) を利用しました。
今回は、Type.GetProperties(Colors) を使いました。
( System.Reflection も使用 )

Colorcombobox_reflection

#
# ColorComboBox_Reflection.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase')
from System.Windows.Markup import XamlReader
from System import Object, Type
from System.Windows import Window, Application, Thickness
from System.Windows.Controls import StackPanel, Button, TextBlock
from System.Windows.Media import Color, Colors, SolidColorBrush

xaml_str="""
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:mscorlib="clr-namespace:System.Reflection;assembly=mscorlib"
    Title="MainWindow" Height="168" Width="244">
    <Window.Resources>
        <DataTemplate x:Key="ColorBoxTemplate" 
                      DataType="{x:Type mscorlib:PropertyInfo}">
            <StackPanel Orientation="Horizontal" Margin="3">
                <Border BorderBrush="Black" BorderThickness="2"
                        CornerRadius="5" Width="20" Height="20"
                        VerticalAlignment="Center"
                        Background="{Binding Path=Name}" />

                <TextBlock Margin="5,0,5,0" Text="{Binding Path=Name}" 
                           VerticalAlignment="Center"/>
            </StackPanel>
        </DataTemplate>
    </Window.Resources>

    <Grid>
        <ComboBox Name="ColorBox" Height="35" Width="200" MaxDropDownHeight="210"
                  ItemTemplate="{StaticResource ColorBoxTemplate}"/>
     </Grid>
</Window>
"""

class ExWindow(Object):
    def __init__(self):
        self.Root = win = XamlReader.Parse(xaml_str)
        self.ColorBox = win.FindName("ColorBox")
        self.ColorBox.Loaded += self.ColorBox_Loaded
        self.ColorBox.SelectionChanged += self.ColorBox_SelectionChanged

    def ColorBox_Loaded(self, sender, e):
        #PropertyInfo[] colorProps = typeof(Colors).GetProperties();
        colorProps = Type.GetProperties(Colors)
        self.ColorBox.ItemsSource = colorProps
        self.ColorBox.SelectedIndex = 0

    def ColorBox_SelectionChanged(self, sender, e):
        selected = self.ColorBox.SelectedItem
        if (selected != None):
            color = selected.GetValue(None, None)
            self.Root.Background = SolidColorBrush(color)

if __name__ == "__main__":
    win = ExWindow()
    Application().Run(win.Root)

IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、動的に IValueConverter を使う

2011-07-04 14:43:57 | DataBinding
e-manual ⇒ WPF(データバインディング). ⇒ もっとも単純なデータバンディング
Slider コントロールの操作結果を TextBox コントロールに表示します。
次のコードは TextBox コントロールの Text プロパティに、
Slider コントロールの Value プロパティをバインドしています。
http://www.kanazawa-net.ne.jp/~pmansato/wpf/wpf_databinding.htm
を参考にしました。 C# から IronPython へ 変換し、動的要素を追加しました。

Ivalueconverter

#
# IValueConverter.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase')
from System import Object,String
from System.Windows.Markup import XamlReader
from System.Windows import Window, Application
from System.Windows.Controls import TextBox
from System.Windows.Data import Binding, BindingOperations, IValueConverter

xaml_str="""
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Binding (IValueConverter)" Height="300" Width="300">
    <!-- 
        xmlns:c="clr-namespace:BindingTest" >
    <Window.Resources>
        <c:IntToHexValueConverter x:Key="valueConverter" />
    </Window.Resources>
    -->
    <StackPanel Orientation="Vertical">
        <!--
        <TextBox Name="textBox1" Width="100" Height="25" HorizontalAlignment="Left" Margin="30,10,0,0"
             Text="{Binding ElementName=slider1, Path=Value, Converter={StaticResource valueConverter}}"/>
        -->
        <TextBox Name="textBox1" Width="100" Height="25" HorizontalAlignment="Left" Margin="30,10,0,0"
             Text="{Binding ElementName=slider1, Path=Value, Converter={x:Null}}"/>
        <Slider Name="slider1" Height="22" Margin="30,20,60,0" Maximum="255" Minimum="0"
            TickPlacement="TopLeft" TickFrequency="16" SmallChange="1" LargeChange="16"
            IsSnapToTickEnabled="True" />
    </StackPanel>
</Window>
"""

class IntToHexValueConverter(IValueConverter):
    def Convert(self,value, targetType, parameter, culture):
        textValue = value
        return String.Format("{0} (0x{1:X2})", int(textValue), int(textValue) )

    def ConvertBack(self,value, TargetType, parameter, culture):
       return Binding.DoNothing
    #// end of IntToHexValueConverter class
 
class ExWindow(Object):
    def __init__(self):
        self.Root = win = XamlReader.Parse(xaml_str)
        self.textBox1 = win.FindName("textBox1")
        self.slider1 = win.FindName("slider1")
        #myBinding = BindingOperations.GetBinding(self.textBox1, TextBox.TextProperty)
        BindingOperations.ClearBinding(self.textBox1, TextBox.TextProperty)
        myBinding = Binding("Value")
        myBinding.Source = self.slider1
        myBinding.Converter = IntToHexValueConverter()
        myBinding.ConverterParameter = "Value"
        self.textBox1.SetBinding(TextBox.TextProperty, myBinding)

if __name__ == "__main__":
    win = ExWindow()
    Application().Run(win.Root)

IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、四角形(Rect)の大きさが変化するアニメーション

2011-07-04 11:58:04 | Animation
プログラムを実行すると、四角形が伸び縮みします。
クリックするとアニメーションを停止し、
再クリックで、再開します。
( Storyboard は使っていません。Animation のみです。)

#
# RectAnimation.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase') # for Rect
from System import Object, TimeSpan
from System.Windows.Markup import XamlReader
from System.Windows import Window, Application, Rect, Duration
from System.Windows.Media import RectangleGeometry
from System.Windows.Media.Animation import RectAnimation, RepeatBehavior

xaml_str="""
<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="RectAnimation2" Width="170" Height="200" Background="Black">
    <Grid>
        <Path Fill="Blue" Stroke="Red" StrokeThickness="1">
            <Path.Data>
                <RectangleGeometry x:Name="myRectangleGeometry" />
            </Path.Data>
        </Path>
    </Grid>
</Window>
"""
# アニメーション部分だけをIronPythonで実装
class ExWindow(object):
    def __init__(self):
        self.Root = win = XamlReader.Parse(xaml_str)
        win.Loaded += self.win_Loaded
        win.MouseLeftButtonDown += self.animation_stop_start

    def win_Loaded(self, sender, e):
        self.myRectAnimation = RectAnimation(
            From = Rect(80, 80, 0, 0),
            To = Rect(30, 30, 100, 100),
            Duration = Duration( TimeSpan.FromSeconds(1) ),
            AutoReverse = True,
            RepeatBehavior = RepeatBehavior.Forever )
 
        self.myRectangleGeometry=self.Root.FindName("myRectangleGeometry")
        self.myRectangleGeometry.BeginAnimation(RectangleGeometry.RectProperty, self.myRectAnimation)
        self.swAnimation = 1       

    def animation_stop_start(self, sender, e):
        if self.swAnimation == 1:
            rect = self.myRectangleGeometry.Rect
            self.myRectangleGeometry.BeginAnimation(RectangleGeometry.RectProperty, None)
            self.myRectangleGeometry.Rect= rect
            self.swAnimation = 0
        else:
            self.myRectangleGeometry.BeginAnimation(RectangleGeometry.RectProperty, self.myRectAnimation)
            self.swAnimation = 1

if __name__ == "__main__":
    win = ExWindow()
    Application().Run(win.Root)

IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、TextEffect 《 FlowDocument 》をアニメーション化する

2011-07-04 04:53:49 | Animation
MSDNを検索していると、興味をひかれるサンプルコードが目にとまった。
http://msdn.microsoft.com/ja-jp/library/ms605762(VS.90).aspx
制御可能なストーリーボードを使用して、
TextEffect をアニメーション化する例を次に示します。
TextEffect は、FrameworkContentElement の名前のスコープに含まれます。

さっそくIronPythonに変換して、実行してみた。
予想以上に、おもしろいサンプルであった。
FlowDocumentという新しい課題が見つかった。
WPFは、機能に富んでいると感じた。

Frameworkcontentelementcontrolstory



#
# FrameworkContentElementControlStoryboardExample.py
#
#/*
#    This example shows how to control
#    a storyboard after it has started.
#*/
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase')

from System import TimeSpan
from System.Windows import Window, Application, NameScope, Thickness, Duration, PropertyPath
from System.Windows.Controls import StackPanel, Button, TextBlock, Orientation
from System.Windows.Media import Brushes, TextEffect,TextEffectCollection
from System.Windows.Media.Animation import Int32Animation, Storyboard
from System.Windows.Documents import Run, Paragraph, BlockUIContainer, FlowDocument

class AnimatingWithStoryboards:
    class FrameworkContentElementControlStoryboardExample(FlowDocument):
        def __init__(self):
            #// Create a name scope for the document.
            NameScope.SetNameScope(self, NameScope())        
            self.Background = Brushes.White;

            #// Create a run of text.
            theText = Run( 
                "Lorem ipsum dolor sit amet, consectetuer adipiscing elit." + 
                "Ut non lacus. Nullam a ligula id leo adipiscing ornare." +
                " Duis mattis. ") 

            #// Create a TextEffect
            animatedSpecialEffect = TextEffect()
            animatedSpecialEffect.Foreground = Brushes.OrangeRed
            animatedSpecialEffect.PositionStart = 0
            animatedSpecialEffect.PositionCount = 0

            #// Assign the TextEffect a name by 
            #// registering it with the page, so that
            #// it can be targeted by storyboard
            #// animations            
            self.RegisterName("animatedSpecialEffect", animatedSpecialEffect)

            #// Apply the text effect to the run.
            theText.TextEffects = TextEffectCollection()
            theText.TextEffects.Add(animatedSpecialEffect)

            #// Create a paragraph to contain the run.
            animatedParagraph = Paragraph(theText)
            animatedParagraph.Background = Brushes.LightGray
            animatedParagraph.Padding = Thickness(20)

            self.Blocks.Add(animatedParagraph)
            controlsContainer = BlockUIContainer()               

            #//
            #// Create an animation and a storyboard to animate the
            #// text effect.
            #//
            countAnimation = Int32Animation(0, 127, TimeSpan.FromSeconds(10))
            Storyboard.SetTargetName(countAnimation, "animatedSpecialEffect")
            Storyboard.SetTargetProperty(countAnimation, 
                PropertyPath(TextEffect.PositionCountProperty))

            self.myStoryboard = Storyboard()
            self.myStoryboard.Children.Add(countAnimation)

            #//
            #// Create some buttons to control the storyboard
            #// and a panel to contain them.
            #//
            buttonPanel = StackPanel()
            buttonPanel.Orientation = Orientation.Vertical

            beginButton = Button()
            beginButton.Content = "Begin"
            beginButton.Click += self.beginButton_Clicked          
            buttonPanel.Children.Add(beginButton)

            pauseButton = Button()
            pauseButton.Content = "Pause"
            pauseButton.Click += self.pauseButton_Clicked
            buttonPanel.Children.Add(pauseButton)

            resumeButton = Button()
            resumeButton.Content = "Resume"
            resumeButton.Click += self.resumeButton_Clicked
            buttonPanel.Children.Add(resumeButton)

            skipToFillButton = Button()
            skipToFillButton.Content = "Skip to Fill"
            skipToFillButton.Click += self.skipToFillButton_Clicked
            buttonPanel.Children.Add(skipToFillButton)

            setSpeedRatioButton = Button()
            setSpeedRatioButton.Content = "Triple Speed"
            setSpeedRatioButton.Click += self.setSpeedRatioButton_Clicked
            buttonPanel.Children.Add(setSpeedRatioButton)

            stopButton = Button()
            stopButton.Content = "Stop"
            stopButton.Click += self.stopButton_Clicked
            buttonPanel.Children.Add(stopButton)

            removeButton = Button()
            removeButton.Content = "Remove"
            removeButton.Click += self.removeButton_Clicked
            buttonPanel.Children.Add(removeButton) 

            controlsContainer.Child = buttonPanel
            self.Blocks.Add(controlsContainer)

        #// Begins the storyboard.
        def beginButton_Clicked(self, sender, args):
            #// Specifying "true" as the second Begin parameter
            #// makes this storyboard controllable.
            self.myStoryboard.Begin(self, True)          

        #// Pauses the storyboard.
        def pauseButton_Clicked(self, sender, args):
            self.myStoryboard.Pause(self)        

        #// Resumes the storyboard.
        def resumeButton_Clicked(self, sender, args):
            self.myStoryboard.Resume(self)        

        #// Advances the storyboard to its fill period.
        def skipToFillButton_Clicked(self, sender, args):
            self.myStoryboard.SkipToFill(self)         

        #// Updates the storyboard's speed.
        def setSpeedRatioButton_Clicked(self, sender, args):
            #// Makes the storyboard progress three times as fast as normal.
            self.myStoryboard.SetSpeedRatio(self, 3)         

        #// Stops the storyboard.
        def stopButton_Clicked(self,sender, args):
            self.myStoryboard.Stop(self)        

        #// Removes the storyboard.
        def removeButton_Clicked(self, sender, args):
             self.myStoryboard.Remove(self);          

    class Window1(Window):
        def __init__(self):
            self.Title = "FrameworkContentElement Control Storyboard Example"
            self.Content = AnimatingWithStoryboards.FrameworkContentElementControlStoryboardExample()

if __name__ == "__main__":
    app = Application()
    app.Run(AnimatingWithStoryboards.Window1())

IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、動的なアニメーションで変化するボタンを作りました

2011-07-02 22:38:08 | Animation
BLOG: Nine Works ==> 動的なアニメーション作成
http://nine-works.blog.ocn.ne.jp/blog/2011/01/post_8f38.html
を参考にさせていただきました。
C#のプログラムをIronPythonに変換しました。
そして、少しアレンジしました。

C#とIronPyhonを比べてみてください。 ( Dynamic Animation )

Photo



#
# 動的なアニメーション作成.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase')

from System.Windows.Markup import XamlReader
from System import Object, TimeSpan
from System.Windows import ( Window, Application, NameScope, Thickness, Duration,
                             PropertyPath, HorizontalAlignment, VerticalAlignment )
from System.Windows.Controls import StackPanel, Button, TextBlock
from System.Windows.Media import Color, Colors, SolidColorBrush
from System.Windows.Media.Animation import Storyboard, RepeatBehavior, DoubleAnimation, ColorAnimation 

xaml_str="""
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="動的なアニメーション作成" Height="200" Width="300">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition />
        </Grid.RowDefinitions>

        <Border BorderBrush="Black" BorderThickness="1" CornerRadius="10" 
            Grid.Row="0" Grid.Column="0" Margin="5" 
            ToolTip="ボタン・アニメーションの種類と動作を指定します。" >
            <StackPanel Orientation="Horizontal" VerticalAlignment="Center" >
                <RadioButton x:Name="radioBig" IsChecked="True" Content="大きくなれ" Margin="10,5"/>
                <RadioButton x:Name="radioSmall" Content="小さくなれ" Margin="10,5" />
                <CheckBox x:Name="stopAnimationCheckBox" Content="アニメーション停止" 
                     HorizontalAlignment="Center" Margin="10,5" />
            </StackPanel>
        </Border>

        <Button Name="button1" Grid.Column="0" Grid.Row="1"
            Width="90" Height="20" Content="おっきくなるよ" 
            HorizontalAlignment="Center" VerticalAlignment="Center" />
    </Grid>
</Window>
"""
class ExWindow(Object):
    def __init__(self):
        win = XamlReader.Parse(xaml_str)
        self.Root = win 
        self.setAttr("button1",win)
        self.setAttr("stopAnimationCheckBox",win)
        self.setAttr("radioBig",win)
        self.setAttr("radioSmall",win)

        self.radioBig.Checked += self.radioBig_Checked
        self.radioSmall.Checked += self.radioSmall_Checked

        self.EXPAND = ( 50.0, ) # タップル  変更不可能

        #// アニメーションを行うコントロールをNameScopeに登録
        #NameScope.SetNameScope(win, NameScope())
        #win.RegisterName(self.button1.Name, self.button1)
        #すでに、登録されているから...

        self.CreateExpandAnimation()

    def setAttr(self, name, xaml):
        x = xaml.FindName(name)
        if x != None : setattr(self, name, x)
        else: print "NameError: '%s' object has no Name '%s'" %(type(xaml),name)

    def CreateExpandAnimation(this):
        #// ボタンの幅を拡大するアニメーション
        #// Byは動的に値を設定するためClickイベントで設定
        this._expandWidthAnimation = DoubleAnimation()
        this._expandWidthAnimation.Duration = Duration(TimeSpan.FromMilliseconds(500))

        #// ボタンの高さを拡大するアニメーション
        #// Byは動的に値を設定するためClickイベントで設定
        this._expandHeightAnimation = DoubleAnimation()
        this._expandHeightAnimation.Duration = Duration(TimeSpan.FromMilliseconds(500))

        #// ストーリーボードを作成
        this._expandStoryboard = Storyboard()
        this._expandStoryboard.Children.Add(this._expandWidthAnimation)
        Storyboard.SetTargetName(this._expandWidthAnimation, this.button1.Name)
        Storyboard.SetTargetProperty(
            this._expandWidthAnimation,
            PropertyPath(Button.WidthProperty))

        this._expandStoryboard.Children.Add(this._expandHeightAnimation)
        Storyboard.SetTargetName(this._expandHeightAnimation, this.button1.Name)
        Storyboard.SetTargetProperty(
            this._expandHeightAnimation,
            PropertyPath(Button.HeightProperty))

        #// イベントハンドラ追加
        this.button1.Click += this.button1_Click

    def button1_Click(self, sender, e):
        if (self.stopAnimationCheckBox.IsChecked == False):
            if (self.radioBig.IsChecked == True): by = self.EXPAND[0]
            else:
                if ( self.button1.Height <= self.EXPAND[0] ) : by = 0.0
                else: by = -self.EXPAND[0]
            if by != 0.0 :
                self._expandWidthAnimation.By = by
                self._expandHeightAnimation.By = by
                self._expandStoryboard.Begin(self.Root)

    def radioBig_Checked(self, sender, e):
        self.button1.Content = "大きくなるよ"

    def radioSmall_Checked(self, sender, e):
        self.button1.Content = "小さくなるよ"

if __name__ == "__main__":
    win = ExWindow()
    Application().Run(win.Root)


IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、3つのSliderからRectangleの背景色を設定 《MultiBinding を使って》

2011-07-02 10:25:57 | DataBinding
e-manual ==> WPF(データバインディング) ==> 複合データバインディング
複合データバインディングとは複数のデータとバインドすることです。
このような場合は、MultiBinding クラスを利用するとともに、
データを変換するクラスを作成しなければなりません。
http://www.kanazawa-net.ne.jp/~pmansato/wpf/wpf_databinding.htm
を参考にしました。C# から IronPython へ 変換。

IronPython から MultiBinding.Converter (IMultiValueConverter) を使用。

Imultivalueconverter_2


#
# IMultiValueConverter.py
#
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase')

from System import Object, String
from System.Windows.Markup import XamlReader
from System.Windows import Window, Application
from System.Windows.Media import Color,SolidColorBrush
from System.Windows.Shapes import Rectangle
from System.Windows.Data import ( Binding,BindingOperations,IValueConverter,
                                  MultiBinding, IMultiValueConverter )
import System

xaml_str="""
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Binding (IMultiValueConverter)" Height="300" Width="320">
  <Window.Resources>
   <Style x:Key="sliderStyle" TargetType="Slider">
      <Setter Property="Width" Value="180" />
      <Setter Property="Minimum" Value="0" />
      <Setter Property="Maximum" Value="255" />
      <Setter Property="LargeChange" Value="16" />
      <Setter Property="SmallChange" Value="1" />
      <Setter Property="TickFrequency" Value="16" />
      <Setter Property="TickPlacement" Value="TopLeft" />
      <Setter Property="IsSnapToTickEnabled" Value="True" />
      <Setter Property="Margin" Value="10" />
    </Style>
  </Window.Resources>
  
  <StackPanel Orientation="Vertical">
    <Slider Name="sliderRed" Style="{StaticResource sliderStyle}" />
    <Slider Name="sliderGreen" Style="{StaticResource sliderStyle}" />
    <Slider Name="sliderBlue" Style="{StaticResource sliderStyle}" />

    <Rectangle Name="rectangle1" Width="200" Height="60" HorizontalAlignment="Center">
      <Rectangle.Fill>
        <SolidColorBrush  x:Name="brush1" />
      </Rectangle.Fill>
    </Rectangle>
  </StackPanel>
</Window>
"""

class ColorConverter(IMultiValueConverter):
    def Convert(self,values, targetType, parameter, culture):
        R = System.Convert.ToByte(values[0])
        G = System.Convert.ToByte(values[1])
        B = System.Convert.ToByte(values[2])  
        return Color.FromRgb(R, G, B)

    def ConvertBack(self,value, targetTypes, parameter, culture):
        return None

class ExWindow(Object):
    def __init__(self):
        win = XamlReader.Parse(xaml_str)
        self.Root = win

        self.rectangle1 = win.FindName("rectangle1")
        self.brush1 = win.FindName("brush1")
        self.sliderRed=win.FindName("sliderRed")
        self.sliderGreen=win.FindName("sliderGreen")
        self.sliderBlue=win.FindName("sliderBlue")

        myMultiBinding = MultiBinding()
        myMultiBinding.Converter = ColorConverter()

        myBinding1 = Binding("Value")
        myBinding1.Source = self.sliderRed
        myBinding1.ConverterParameter = "Value"

        myBinding2 = Binding("Value")
        myBinding2.Source = self.sliderGreen
        myBinding2.ConverterParameter = "Value"

        myBinding3 = Binding("Value")
        myBinding3.Source = self.sliderBlue
        myBinding3.ConverterParameter = "Value"

        myMultiBinding.AddChild(myBinding1)
        myMultiBinding.AddChild(myBinding2)
        myMultiBinding.AddChild(myBinding3)

        BindingOperations.SetBinding(self.brush1,
                                     SolidColorBrush.ColorProperty,
                                     myMultiBinding)

if __name__ == "__main__":
    win = ExWindow()
    Application().Run(win.Root)

IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社

IronPythonで、カウンターを作りました《 MVVM を使って 》

2011-07-02 04:32:03 | DataBinding
Blog:"[WPF]レイアウトに飽きてきたのでバインディングしてみる"
http://blogs.wankuma.com/kazuki/archive/2007/10/13/101894.aspx
を参考にしました。C# から IronPython へ変換しました。

MVVM 処理を追加しました。

Counterdatabindingnew


#
# CounterDataBindingNew.py
#      MVVM を使用!
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase')

from System import Object
from System.Windows.Markup import XamlReader
from System.Windows import Window, Application, MessageBox
from System.Windows.Controls import Label
from System.Windows.Data import Binding,IValueConverter
from System.ComponentModel import INotifyPropertyChanged
from System.ComponentModel import PropertyChangedEventArgs

xaml_str="""
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="NewDataBinding" Width="220" SizeToContent="Height">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto" />
            <ColumnDefinition />
        </Grid.ColumnDefinitions> 

        <Label Content="値:" Grid.Row="0" Grid.Column="0" />
        <Label Name="valueLabel" Grid.Row="0" Grid.Column="1" 
               Content="ここに値がきますよと" />
        <Label Content="概要:" Grid.Row="1" Grid.Column="0" />
        <Label Name="descriptionLabel" Grid.Row ="1" Grid.Column="1" 
               Content="ここに概要がきますよと" /> 

        <StackPanel Grid.Row="2" Grid.Column="1" 
                    Orientation="Horizontal" HorizontalAlignment="Right">
            <Button Name="incrButton" Content="インクリメント" Margin="2" />
            <Button Name="decrButton" Content="デクリメント" Margin="2" />
            <Button Name="dumpButton" Content="Dump" Margin="2" />
        </StackPanel>
    </Grid>
</Window>
"""
class ViewModelBase(INotifyPropertyChanged):
     def __init__(self):
         self.propertyChangedHandlers = []
     def RaisePropertyChanged(self, propertyName):
         args = PropertyChangedEventArgs(propertyName)
         for handler in self.propertyChangedHandlers:
             handler(self, args)
     def add_PropertyChanged(self, handler):
         self.propertyChangedHandlers.append(handler)
     def remove_PropertyChanged(self, handler):
         self.propertyChangedHandlers.remove(handler)

class Counter(ViewModelBase):
    def __init__(self):
        ViewModelBase.__init__(self)
        self._Value = 0
        self._Description = ""

    def _getValue(self):
        return self._Value
    def _setValue(self,value):
        self._Value = value
        self.RaisePropertyChanged("Value")
    Value = property(_getValue, _setValue)

    def _getDescription(self):
        return self._Description
    def _setDescription(self,description):
        self._Description = description
        self.RaisePropertyChanged("Description")
    Description = property(_getDescription, _setDescription)

    def Incr(self):
        self.Value += 1

    def Decr(self):
        self.Value -= 1

class ExWindow(Object):
    def __init__(self):
        xaml = XamlReader.Parse(xaml_str)
        self.Root = xaml

        self.setAttr("valueLabel",xaml)
        self.setAttr("descriptionLabel",xaml)
        self.setAttr("incrButton",xaml)
        self.setAttr("decrButton",xaml)
        self.setAttr("dumpButton",xaml)

        self.incrButton.Click += self.incrButton_Click
        self.decrButton.Click += self.decrButton_Click
        self.dumpButton.Click += self.dumpButton_Click

        #// カウンタを作る
        self.counter = Counter()
        self.counter.Description = "これはサンプル用のカウンタです"

        #// Bainding の設定
        self.InitializeBinding()

    def setAttr(self, name, xaml):
        x = xaml.FindName(name)
        if x != None: setattr(self, name, x)
        else: print "NameError: '%s' object has no Name '%s'" %(type(xaml),name)

    def InitializeBinding(self):
        valueBinding = Binding("Value")
        self.valueLabel.SetBinding(Label.ContentProperty, valueBinding) 
        descriptionBinding = Binding("Description")
        self.descriptionLabel.SetBinding(Label.ContentProperty, descriptionBinding)
        #// カウンタをDataContextに!
        self.Root.DataContext = self.counter

    def incrButton_Click(self,sender, e):
        self.counter.Incr()

    def decrButton_Click(self, sender, e):
        self.counter.Decr()

    def dumpButton_Click(self, sender, e):
        #// カウンタの中身を確認
        MessageBox.Show("%d: %s"  % (self.counter.Value, self.counter.Description) )

if __name__ == "__main__":
    win = ExWindow()
    Application().Run(win.Root)


IronPythonの世界 (Windows Script Programming)
荒井 省三
ソフトバンク クリエイティブ
エキスパートPythonプログラミング
Tarek Ziade
アスキー・メディアワークス
Pythonスタートブック
辻 真吾
技術評論社