您的位置:首页 > 其它

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

2015-05-26 11:00 399 查看
一、WPF绑定各种数据源索引

WPF绑定各种数据源之Datatable

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

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

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

WPF绑定基础

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

1.绑定Value路径

<TextBlockMargin=
"327,378,331,363"
Name=
"textBlock1"
Text=
"{BindingElementName=slider1,Path=Value}"
/>

<SliderHeight=
"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:

<TextBoxHeight=
"23"
HorizontalAlignment=
"Left"
Margin=
"37,48,0,0"
Name=
"textBox1"
Text=
"{Binding
Path=Text.Length,ElementName=textBox2,Mode=OneWay}"

VerticalAlignment=
"Top"
Width=
"120"
/>

<TextBoxHeight=
"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、绑定到索引器

<TextBoxHeight=
"23"
HorizontalAlignment=
"Left"
Margin=
"37,48,0,0"
Name=
"textBox1"
Text=
"{Binding
Path=Text.[2],ElementName=textBox2,Mode=OneWay}"

VerticalAlignment=
"Top"
Width=
"120"
/>

<TextBoxHeight=
"23"
HorizontalAlignment=
"Left"
Text=
"WorkHard"
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:Stringx:Key=
"myStr"
>

WorkHandWorkSmart

</sys:String>

</Window.Resources>


XAML:

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


下面的代码可以写成Text="{BindingPath=.,Source={StaticResourceResourceKey=myStr},Mode=OneWay}"或Text="{BindingSource={StaticResourceResourceKey=myStr},Mode=OneWay}"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: