WPF还撑持控件作为数据源,
<TextBox Name="txt_Source" Width="120" HorizontalAlignment="Left"></TextBox> <TextBox Text="{Binding ElementName=txt_Source,Path=Text}" Name="txt_Target" Width="120" HorizontalAlignment="Left">
上面代码就可以实现控件之间的双向绑定,我们发明我们的绑定数据源不是Source,而是ElementName.
固然我们也可以使用代码来实现
Binding binding = new Binding("Text") { Source = this.txt_Source }; this.txt_Target.SetBinding(TextBox.TextProperty, binding);
使用代码绑定我们依然使用的Source来绑定数据源
2.多级路径WPF撑持多级路径,也就是我们通俗的说“点”下去。
我们改下上面的代码
Binding binding = new Binding("Text.Length") { Source =this.txt_Source,Mode = BindingMode.OneWay }; this.txt_Target.SetBinding(TextBox.TextProperty, binding);
注意:因为源数据和方针数据无法做到匹配,所以无法双向绑定。
我们可以看到我们绑定的数据是Text属性中的Length属性,这就是我们所谓的多级路径.
3.索引绑定我们知道,调集类型是索引器(Indexer)又称为带参属性。既然是属性,索引器也能作为Path来使用,好比我们想让一个TextBox显示此外一个TextBox的第1个字符
Binding binding = new Binding("Text[1]") { Source =this.txt_Source,Mode = BindingMode.OneWay }; this.txt_Target.SetBinding(TextBox.TextProperty, binding);
4.调集绑定
当使用一个调集或者DataView做为数据源时,如果我们想把它默认的元素做为数据源使用,则需要使用下面的语法:
List<string> list = new List<string>() { "狗娃","狗剩2"}; txt_List1.SetBinding(TextBox.TextProperty, new Binding("/") { Source = list, Mode = BindingMode.OneTime }); txt_List2.SetBinding(TextBox.TextProperty, new Binding("/[1]") { Source = list,Mode = BindingMode.OneTime }); txt_List3.SetBinding(TextBox.TextProperty, new Binding("/Length") { Source = list, Mode = BindingMode.OneTime });
效果如下
如果想要绑定绑定第二个元素,则直接使用"点"即可
List<string> list = new List<string>() { "狗娃","狗剩2"}; txt_List1.SetBinding(TextBox.TextProperty, new Binding("[1]") { Source = list, Mode = BindingMode.OneTime }); txt_List2.SetBinding(TextBox.TextProperty, new Binding("[1].[1]") { Source = list,Mode = BindingMode.OneTime }); txt_List3.SetBinding(TextBox.TextProperty, new Binding("[1].Length") { Source = list, Mode = BindingMode.OneTime });
如果想把子集调集中元素作为Path,可以使用多级斜线要领(一路"斜线"下去);
我们创建一个省市区关系的类型
public class Province { public string Name { get; set; } public IList<City> Citys { get; set; } } public class City { public string Name { get; set; } public IList<District> Districts { get; set; } } public class District { public string Name { get; set; } }
然后我们使用多级斜线进行绑定
List<Province> list = new List<Province>() { new Province { Name ="河北", Citys = new List<City> { new City { Name = "邯郸", Districts = new List<District>{ new District { Name="邯山区"} } } } } }; txt_List1.SetBinding(TextBox.TextProperty, new Binding("/Name") { Source = list, Mode = BindingMode.OneTime }); txt_List2.SetBinding(TextBox.TextProperty, new Binding("/Citys/Name") { Source = list, Mode = BindingMode.OneTime }); txt_List3.SetBinding(TextBox.TextProperty, new Binding("/Citys/Districts/Name") { Source = list, Mode = BindingMode.OneTime });
固然也可以使用多级"点"进行绑定