IronPython にて WPF の DataBinding をコードで行う方法が解らなかった。
ElementName をコードで書き込んでも反映されないし。
ということで毎度のように検索、C# コードなら日本語で見つかるから便利だね。
コードで行うには Source Property か DataContext を利用すればいいのか。
XAML を含めて IronPython でやってみよう。
Source Version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | # -*- coding: UTF-8 -*- import clr clr.AddReferenceByPartialName( "PresentationCore" ) clr.AddReferenceByPartialName( "PresentationFramework" ) clr.AddReferenceByPartialName( "WindowsBase" ) from System import * from System.Windows import * from System.Windows.Controls import * class DataBindingTest(Window): """ Source Version """ def __init__( self ): # Create Controls textbox = TextBox() textblock = TextBlock() # Append stackpanel = StackPanel() stackpanel.Children.Add(textbox) stackpanel.Children.Add(textblock) self .Content = stackpanel self .SizeToContent = SizeToContent.WidthAndHeight # Binding binding = Data.Binding( "Text" ) binding.Source = textbox textblock.SetBinding(TextBlock.TextProperty, binding) if __name__ = = "__main__" : Application().Run(DataBindingTest()) |
DataContext Version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | # -*- coding: UTF-8 -*- import clr clr.AddReferenceByPartialName( "PresentationCore" ) clr.AddReferenceByPartialName( "PresentationFramework" ) clr.AddReferenceByPartialName( "WindowsBase" ) from System import * from System.Windows import * from System.Windows.Controls import * class DataBindingTest(Window): """ DataContext Version """ def __init__( self ): # Create Controls textbox = TextBox() textblock = TextBlock() # Append stackpanel = StackPanel() stackpanel.Children.Add(textbox) stackpanel.Children.Add(textblock) self .Content = stackpanel self .SizeToContent = SizeToContent.WidthAndHeight # Set DataContext self .DataContext = textbox # Binding binding = Data.Binding( "Text" ) textblock.SetBinding(TextBlock.TextProperty, binding) if __name__ = = "__main__" : Application().Run(DataBindingTest()) |
XAML Version
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | # -*- coding: UTF-8 -*- import clr clr.AddReferenceByPartialName( "PresentationCore" ) clr.AddReferenceByPartialName( "PresentationFramework" ) clr.AddReferenceByPartialName( "WindowsBase" ) from System.Windows import Application from System.Windows.Markup import XamlReader xaml = """<Window SizeToContent = "WidthAndHeight"> <StackPanel> <TextBox Name="_tname" /> <TextBlock Text="{Binding ElementName=_tname, Path=Text}" /> </StackPanel> </Window>""" w = XamlReader.Parse(xaml) Application().Run(w) |
どれでも結果は同じ、TextBox に書き込んだ文字列がそのまま TextBlock に。
DataContext はバインディング元データが一つなら問題無いだろうけどチト怖いかな。
というより、やはりこういうのは XAML が一番解りやすく書けますね。
用途によってコードにするか XAML にするかで選べばいいことだけど。