Overview of Data Binding
The data-binding model in WPF provides a consistent and convenient way for applications to interact with data. Elements that are bound to the data can reflect changes automatically, a broad range of properties inherently supports data binding, and data conversion happens by default in WPF, when possible. Additionally, you can create customized data bindings, notifications, data converters, and validation rules to meet the needs of your application.
Creating a Data Binding
WPF supports the binding of a broad range of properties to various data sources including managed objects, XML data, and UI elements. You establish a binding by using the Binding object. Each binding usually has four components: binding target, target property, binding source, and a path to the source value.
在 XAML 中使用绑定:
使用Binding的标记,可以把目标属性绑定到静态资源<StaticResouce>或者其他XAML的元素(包括自身)
1)绑定到其他XAML元素 <Label Content="{Binding ElementName=其他元素的名称, Path=源对象的属性}">
2)绑定到静态资源 <Label Content="{Binding Resource={StaticResouce ResourceKey名称}}">
3)绑定到自身,用RelativeSource; Content="{Binding RelativeSource={RelativeSource Self}, Path=源对象的属性}"
4)绑定到任意.NET对象;SetBinding();同时要对源数据实现INotifiyPropertyChanged接口。
5) 源对象可以是任意属性,但是目标对象只能是DependencyProperty。
Implementing Property Change Notification
You can configure data bindings to automatically propagate changes between the source property and the target property. Property change notifications enable the target property to remain synchronized with the source property. The UpdateSourceTrigger property specifies when changes to the target property are propagated to the source.
Converting Data
Whenever possible, WPF will convert incompatible data types between properties in a data binding. You can also implement a custom value converter to translate between data types in a data binding.
Validating Data
Validation occurs each time an input value is transferred to the binding source property; this occurs before the relevant converter is called. WPF enables you to implement validation logic for your applications by associating WPF validation rules with a binding object. Additionally, you can create and implement custom validation rules.