一、binding的一般步驟
1,準備資料源
資料源需要實作INotifyPropertyChanged接口
例如:
class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string name;
public string Name
{
get { return name; }
set
{
name = value;
//觸發事件
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs("Name"));
}
}
}
}
2,準備Binding對象
Person p = new Person("D-boy");
Binding binding = new Binding();
binding.Source = p;
binding.Path = new PropertyPath("Name");
3,用Binding對象将資料源和目标連結
假如在XAML處添加了一個TextBlock目标
<TextBlock x:Name="txtName"></TextBlock>
那麼可以使用BindingOperations.SetBinding()方法将其進行binding了。
BindingOperations.SetBinding(txtName, TextBlock.TextProperty, binding);
也可以使用UI元素的基類FramworkElement封裝的SetBinding函數
txtName.SetBinding(TextBlock.TextProperty, binding);
将上面兩步結合在一起可以這樣寫
txtName.SetBinding(TextBlock.TextProperty, new Binding("Name") { Source=p});
二、控件間的Binding
XAML處如下兩個控件
<TextBox x:Name="txt1" />
<TextBlock x:Name="txt2" Text="{Binding Path=Text, ElementName=txt1}" />
如果要改變Binding源的觸發事件,可以設定Binding的UpdateSourceTrigger屬性為LostFocus、Explicit、PropertyChanged中的一種。
三、Binding的Path
1,Path的設定
如上例,
XAML處為
<TextBlock x:Name="txt2" Text="{Binding Path=Text, ElementName=txt1}" />
或是
<TextBlock x:Name="txt2" Text="{Binding Text, ElementName=txt1}" />
相應的C#代碼為
txt2.SetBinding(TextBlock.TextProperty, new Binding(){ Path=new PropertyPath("Value"),Source=txt1});
txt2.SetBinding(TextBlock.TextProperty, new Binding("Text") { Source=txt1});
之類的...
2,Path還支援一路點下去~~
比如
<TextBlock x:Name="txt2" Text="{Binding Text.Length, ElementName=txt1}" />
<TextBlock x:Name="txt2" Text="{Binding Text.[2], ElementName=txt1}" />
3,當資料源本身就是資料的時候,Path為.
window添加命名空間
xmlns:sys="clr-namespace:System;assembly=mscorlib"
添加資源
<Window.Resources>
<sys:String x:Key="string">
string!!!!!
</sys:String>
</Window.Resources>
使用Binding
<TextBlock x:Name="txt2" Text="{Binding ., Source={StaticResource ResourceKey=string}}" />
精簡為
<TextBlock x:Name="txt2" Text="{Binding Source={StaticResource ResourceKey=string}}" />
當然這樣的情況,我就直接
<TextBlock x:Name="txt2" Text="{StaticResource ResourceKey=string}" />
-_- !