WPF绑定各种数据源之元素控件属性

一、WPF绑定各种数据源索引

WPF 绑定各种数据源之Datatable

WPF绑定各种数据源之object数据源

WPF绑定各种数据源之xml数据源

WPF绑定各种数据源之元素控件属性

WPF 绑定基础

二、WPF绑定各种数据源之元素控件属性

1.绑定Value路径

<TextBlock Margin= "327,378,331,363"  Name= "textBlock1"   Text= "{Binding ElementName=slider1, Path=Value}"   />
  <Slider Height= "22"  Minimum= "0"  Maximum= "100"  HorizontalAlignment= "Left"  Margin= "135,346,0,0"  Name= "slider1"  VerticalAlignment= "Top"  Width= "100"  />

与上面等效的C#代码如下:

textBlock1.SetBinding(TextBlock.TextProperty, new  Binding() { Path = new  PropertyPath( "Value" ), Source = slider1});

效果图:

 

2、绑定到Text.Length路径

XAML:

<TextBox Height= "23"  HorizontalAlignment= "Left"  Margin= "37,48,0,0"  Name= "textBox1"  Text= "{Binding Path=Text.Length, ElementName=textBox2, Mode=OneWay}"
                 VerticalAlignment= "Top"  Width= "120"  />
  <TextBox Height= "23"  HorizontalAlignment= "Left"  Margin= "37,92,0,0"  Name= "textBox2"  VerticalAlignment= "Top"  Width= "120"  />

与上面等效的C#代码如下:

textBox1.SetBinding(TextBox.TextProperty, new  Binding() { Path = new  PropertyPath( "Text.Length" ),Source = textBox2, Mode=BindingMode.OneWay});

3、绑定到索引器

<TextBox Height= "23"  HorizontalAlignment= "Left"  Margin= "37,48,0,0"  Name= "textBox1"  Text= "{Binding Path=Text.[2], ElementName=textBox2, Mode=OneWay}"
                  VerticalAlignment= "Top"  Width= "120"  />
<TextBox Height= "23"  HorizontalAlignment= "Left"  Text= "Work Hard"   Margin= "37,92,0,0"  Name= "textBox2"  VerticalAlignment= "Top"  Width= "120"  />

此处等效的C#代码略

4、如果Binding的源是集合时,使用默认元素当Path使用,则语法如下

List< string > strCityList = new  List< string >() { "Hangzhou" , "Shanghai" , "Beijing"  };
textBox3.SetBinding(TextBox.TextProperty, new  Binding( "/" ) { Source = strCityList });
textBox4.SetBinding(TextBox.TextProperty, new  Binding( "/Length" ){Source = strCityList, Mode = BindingMode.OneWay});
textBox5.SetBinding(TextBox.TextProperty, new  Binding( "/[3]" ) { Source = strCityList, Mode = BindingMode.OneWay });

效果图如下:

               

 

5.没有Path的绑定

这是一种特殊的情况,Binding源本身就是数据且不需要Path来指明,string、int等基本类型就是这样,他们本身就是数据,无法指出通过那个属性访问这个数据,这时我们只需将Path设置成"."就可以了。请看下面的代码:

<Window.Resources>
     <sys:String x:Key= "myStr" >
         Work Hand Work Smart
     </sys:String>
</Window.Resources>

XAML:

<TextBox Height= "23"  HorizontalAlignment= "Right"  Margin= "0,65,199,0"  Text= "{Binding Path=. ,Source={StaticResource ResourceKey=myStr}, Mode=OneWay}"   Name= "textBox6"  VerticalAlignment= "Top"  Width= "141"  />

 下面的代码可以写成Text="{Binding Path=. ,Source={StaticResource ResourceKey=myStr}, Mode=OneWay}" 或Text="{Binding Source={StaticResource ResourceKey=myStr}, Mode=OneWay}"

 

 

 

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值