myBlog

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

IronPythonでColorComboBoxをつくりました

2011-07-01 23:21:17 | IronPython

IronPythonで色を選択するComboBoxをつくりました.。

XAML と IronPythonを1つのファイルに、まとめています。

Colorcombobox

#
# ColorComboBox.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, CornerRadius, Thickness
from System.Windows.Controls import (StackPanel, Border, Orientation,
                    ComboBoxItem, ComboBoxItem, TextBlock )
from System.Windows.Media import Color, Colors, SolidColorBrush, Brushes

xaml_str="""
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Color ComboBox" Height="62" Width="220" >
  <ComboBox Name="comboBox1" Height ="25" MaxDropDownHeight="338"/>
</Window>
"""

class ExWindow(Object):
    def __init__(self):
        win = XamlReader.Parse(xaml_str)
        self.Root = win
        self.comboBox1 = win.FindName("comboBox1")
        win.Loaded += self.window1_Loaded

    def window1_Loaded(self, sender, e):
        self.SetupComboBox()
        if (self.comboBox1.Items.Count > 0):
           self.comboBox1.SelectedIndex = 0

    def SetupComboBox(self):
        item = ComboBoxItem()

        infs=[]
        for name in dir(Colors):
            c = getattr(Colors, name)
            if isinstance(c, Color):
                infs.append([name, SolidColorBrush(c)])

        for name, col in infs:
            brush = col
            item = ComboBoxItem()

            panel = StackPanel()
            panel.Orientation = Orientation.Horizontal

            border = Border()
            border.Background = brush
            border.CornerRadius = CornerRadius(3)
            border.Width = 30
            border.Height = 12
            border.BorderBrush = Brushes.Black
            border.BorderThickness = Thickness(1)

            block = TextBlock()
            block.Text = name
            block.Width = self.comboBox1.Width - border.Width - 20
            block.Margin = Thickness(10, 0, 0, 0)

            panel.Children.Add(border)
            panel.Children.Add(block)

            item.Content = panel
            self.comboBox1.Items.Add(item)

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

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

IronPython で TemplateBinding を使う

2011-07-01 21:53:49 | IronPython
IronPython で TemplateBinding を使用 Charles Petzold のC#プログラムを IronPython に変換しました。

Sample

#// 
#// Charles Petzold has a nice sample on how to create ControlTemplate in code.
#// http://www.netframeworkdev.com/windows-presentation-foundation-wpf/control-templates-88275.shtml
#// sample.py
#//  
import clr
clr.AddReferenceByPartialName("PresentationFramework")
clr.AddReferenceByPartialName("PresentationCore")
clr.AddReference('WindowsBase')

from System.Windows import (Window, Application, Style, Setter,
                    Thickness, FrameworkElementFactory, SystemColors,
                    HorizontalAlignment, VerticalAlignment,
                    TemplateBindingExtension, MessageBox, Trigger,
                    UIElement, CornerRadius, FontStyles )
from System.Windows.Controls import (Button, Border, Control, 
                    ControlTemplate, ContentPresenter )
from System.Windows.Media import Color, Colors, SolidColorBrush, Brushes

class Window1(Window):
    def __init__(self):
        self.Title = "Build Button Factory"
        self.Width = 700
        self.Height = 250
        #// Create a ControlTemplate intended for a Button object.
        template = ControlTemplate(Button) #(typeof(Button));

        #// Create a FrameworkElementFactory for the Border class.
        factoryBorder = FrameworkElementFactory(Border)

        #// Give it a name to refer to it later.
        factoryBorder.Name = "border"

        #// Set certain default properties.
        factoryBorder.SetValue(Border.BorderBrushProperty, Brushes.Red)
        factoryBorder.SetValue(Border.BorderThicknessProperty, Thickness(3))
        factoryBorder.SetValue(Border.BackgroundProperty, SystemColors.ControlLightBrush )

        #// Create a FrameworkElementFactory for the ContentPresenter class.
        factoryContent = FrameworkElementFactory(ContentPresenter)

        #// Give it a name to refer to it later.
        factoryContent.Name = "content"

        #// Bind some ContentPresenter properties to Button properties.
        factoryContent.SetValue(ContentPresenter.ContentProperty,
                                TemplateBindingExtension(Button.ContentProperty))

        #// Notice that the button's Padding is the content's Margin!
        factoryContent.SetValue(ContentPresenter.MarginProperty,
                                TemplateBindingExtension(Button.PaddingProperty))

        #// Make the ContentPresenter a child of the Border.
        factoryBorder.AppendChild(factoryContent)

        #// Make the Border the root element of the visual tree.
        template.VisualTree = factoryBorder

        #// Define a new Trigger when IsMouseOver is true
        trig = Trigger()
        trig.Property = UIElement.IsMouseOverProperty
        trig.Value = True

        #// Associate a Setter with that Trigger to change the
        #// CornerRadius property of the "border" element.
        set = Setter()
        set.Property = Border.CornerRadiusProperty
        set.Value = CornerRadius(24)
        set.TargetName = "border"

        #// Add the Setter to the Setters collection of the Trigger.
        trig.Setters.Add(set)

        #// Similarly, define a Setter to change the FontStyle.
        #// (No TargetName is needed because it's the button's property.) 
        set = Setter()
        set.Property = Control.FontStyleProperty
        set.Value = FontStyles.Italic

        #// Add it to the same trigger's Setters collection as before.
        trig.Setters.Add(set)

        #// Add the Trigger to the template.
        template.Triggers.Add(trig)

        #// Similarly, define a Trigger for IsPressed.
        trig = Trigger()
        trig.Property = Button.IsPressedProperty
        trig.Value = True

        set = Setter()
        set.Property = Border.BackgroundProperty
        set.Value = SystemColors.ControlDarkBrush
        set.TargetName = "border"

        #// Add the Setter to the trigger's Setters collection.
        trig.Setters.Add(set)

        #// Add the Trigger to the template.
        template.Triggers.Add(trig)

        #// Finally, create a Button.
        btn = Button()

        #// Give it the template.
        btn.Template = template

        #// Define other properties normally.
        btn.Content = "Button with Custom Template"
        btn.Padding = Thickness(20)
        btn.FontSize = 48
        btn.HorizontalAlignment = HorizontalAlignment.Center
        btn.VerticalAlignment = VerticalAlignment.Center
        btn.Click += self.ButtonOnClick

        self.Content = btn

    def ButtonOnClick(self, sender, args):
        MessageBox.Show("You clicked the button", self.Title)

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

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