work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

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

Posted on 2011-09-06 14:11  work hard work smart  阅读(12272)  评论(0编辑  收藏  举报

一、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}"