Data binding through code
Data binding is implemented through code, using the binding class of the System.Windows.Data namespace, which uses the following properties of the binding class mainly:
Source property: Data sources that are bound to
Mode property: The pattern of the binding (onetime, OneWay, TwoWay, OneWayToSource, or default)
Path attribute: The property of the data source that is bound to
Converter property: Type converter to use when binding
Use the SetBinding method on the bound target control to add data binding. For example, bind the MyData Name property to the Text property of the Txtname control, and use the Mycolorconverter converter to bind the Mybindingcolor Colorobject property to the Fill property of the Rec control:
1: MyData data = new MyData();
2:
3: Binding binding1 = new Binding();
4: binding1.Source = data;
5: binding1.Mode = BindingMode.OneWay;
6: binding1.Path = new PropertyPath("Name");
7:
8: txtName.SetBinding(TextBox.TextProperty, binding1);
9:
10:
11: MyBindingColor color = new MyBindingColor();
12:
13: Binding binding2 = new Binding();
14: binding2.Source = color;
15: binding2.Mode = BindingMode.OneWay;
16: binding2.Path = new PropertyPath ("ColorObject");
17: binding2.Converter = new MyColorConverter();
18:
19: rec.SetBinding (Rectangle.FillProperty, binding2);
Second, the implementation of binding data validation:
For the validation of bound data, the system uses the following mechanism:
You can associate Validationrules with a Binding object by using the WPF data-binding model. When the property of the binding target passes the property value to the binding source property (TwoWay mode or OneWayToSource mode only), the Validate method in the ValidationRule is executed to validate the interface input data.