WPF的数据绑定
1)数据绑定模型
数据绑定模型由五部分组成:DependencyObject(目标对象)、目标属性、Object(数据源对象)、数据源属性以及起连接作用的Binding的绑定对象。
2)数据的绑定方向
- 通过Binding 的Mode属性设置数据绑定的方向
OneWay:从数据源到目标对象即目标对象会随数据源改变而改变;
TwoWay:双向改变;
OneWayToSource:从目标对象到数据源即通过目标对象更新数据源对象的某些属性。 - 实现随数据源属性改变的DependencyObject更新
数据源实现INotifyPropertyChanged接口分两步:
第一步:让该类继承接口INotifyPropertyChanged接口并实现PropertyChanged事件
第二步:设置属性在每一次调用时使用Notify()函数触发PropertyChanged事件
<Grid>
<Button Content="修改" HorizontalAlignment="Left" Margin="104,142,0,0" VerticalAlignment="Top" Width="94" Height="27" Click="Button_Click" />
<Button Content="下一个" HorizontalAlignment="Left" Margin="313,142,0,0" VerticalAlignment="Top" Width="89" Height="27"/>
<TextBlock HorizontalAlignment="Left" Margin="130,46,0,0" TextWrapping="Wrap" Text="姓名:" VerticalAlignment="Top" Height="23" Width="68" FontSize="16"/>
<TextBox Name="txbName" HorizontalAlignment="Left" Height="23" Margin="268,46,0,0" TextWrapping="Wrap" Text="{Binding Source={StaticResource ronger},Path=Name}" VerticalAlignment="Top" Width="120"/>
<TextBlock HorizontalAlignment="Left" Margin="130,86,0,0" TextWrapping="Wrap" Text="年龄:" VerticalAlignment="Top" Height="23" Width="68" FontSize="16"/>
<TextBox Name="txbAge" HorizontalAlignment="Left" Height="23" Margin="268,86,0,0" TextWrapping="Wrap" Text="{Binding Source={StaticResource ronger},Path=Age,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Top" Width="120"/>
</Grid>
public class Person:INotifyPropertyChanged
{
string name;
public event PropertyChangedEventHandler PropertyChanged;
void Notify(string proName)
{
if (this.PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(proName));
}
}
public string Name
{
get { return this.name; }
set
{
if (this.name == value) { return; }
this.name = value;
Notify("Name");
}
}
int age;
public int Age
{
get { return this.age; }
set
{
if (this.age == value) { return; }
this.age = value;
Notify("Age");//触发修改事件
}
}
public Person() { }
public Person( string name,int age)
{
this.age = age;
this.name = name;
}
}
- 数据绑定的触发条件
UpdateSourceTrigger的设置
(1)LostFocus:目标对象失去焦点时更新数据源
(2)PropertyChanged:更新数据源的属性时DependencyObject的属性才会改变
(3)Explicit:只有显示通知才会更新数据源
(4)Default:默认和LostFocus相同 - 绑定数据源的几种方式:
(1)Source:适用于数据源为普通的.Net对象
(2)Element:多用于元素之间的绑定,通过滑块控件改变文本框字字体大小
(3)RelativeSource:如果数据源需要指定相对位置时(FindAncestor、Self、PreviousData、TemplatedParent)
FindAncestor:沿着元素树向上查找
Self:数据源自生为目标对象,用来绑定目标对象的A属性和B属性
PreviousData:多用在列表中,表示前一个列表项
(4)TemplatedParent:表示拥有该模板的父类