关于WPF绑定机制,给我们带来了很大的方便,我们都了解在WPF绑定中使用XAML方式可以这样做,代码如下:
1 |
< Window x:Class = "WpfApplication1.Window1" |
4 |
Title = "Window1" Height = "300" Width = "300" > |
6 |
< TextBlock Name = "txtbShow" Height = "21" Margin = "47,32,111,0" VerticalAlignment = "Top" Text = "{Binding ElementName=txtInput,Path=Text}" /> |
7 |
< TextBox Name = "txtInput" Height = "23" Margin = "47,70,111,0" VerticalAlignment = "Top" /> |
但是如果在cs文件中如何进行控件的绑定呢?看下面代码:
2 |
Binding textBinding = new Binding(); |
4 |
textBinding.Source = this .txtInput; |
6 |
textBinding.Path = new PropertyPath( "Text" ); |
8 |
this .txtbShow.SetBinding(TextBlock.TextProperty, textBinding); |
从上面代码可以看出,WPF用代码的方式也能很好的进行绑定操作。如果我们要执行双向绑定,或者设置Converter的时候怎么办呢?我们只要设置Binding的这两个属性Binding.Converter,Binding.Mode就可以了。