The words binding of the learning notes of the "in Layman's WPF"

Source: Internet
Author: User

The binding acts as a bridge to the data, and its ends are the source of the binding and the target, which is used to send the data in source to target and return the change in target to source. In general, the source of the binding is the object of the logical layer, and the target is the control object of the UI layer.

Basic methods of use of binding

If you want an object that is a data source to be automatically displayed to the interface when changes occur, the object of the data source needs to implement the INotifyPropertyChanged interface. When you set a binding, you specify which property is bound to the data source, which is called the path to the binding. Binds the binding object to the target through a bind method, specifying which attribute the data is to be served to the target, and the target's binding property must be a dependency property. Example code:

            New Binding ();             = DateTime.Now;             New PropertyPath ("year");            Bindingoperations.setbinding (Txtblock, textblock.textproperty, binding);             // txtblock.setbinding (textblock.textdecorationsproperty, binding);

Setting bindings can also be achieved by FrameworkElement's SetBinding method.

Data source for binding

If you want to automatically notify the binding update UI when the data source object changes, you need the source object to implement the INotifyPropertyChanged interface. In addition to ordinary objects as data sources, you can also use other controls, collections, XML data, and so on as a data source.

To associate a control's properties to another control's property through a markup extension, sample code:

        <textbox text="{Binding Path=value,elementname=slider}"></TextBox>        <slider x:name="Slider"></Slider>

The attribute that controls the flow of the binding data is mode, type Bindingmode enumeration, TwoWay: Bidirectional flow, OneWay: From the source to the target, OneTime: Read only once, OneWayToSource: from the target to the source, Default: According to the actual situation of the target to determine, if the target is editable is twoway, if the target is read-only, then oneway. You can specify the time when target updates the source by changing the UpdateSourceTrigger property of the binding. Additional events sourceupdated and targetupdated that listen to the binding can also be added to the target element to listen for updates to the source and destination.

When specifying the path to the data source for the binding, you can use the "." Operators, such as Property.property, can even use indexers such as property. [1] or property[1]. If the source of the binding is a collection, if you want to get the first element as the path to the binding, use "/" to get the first element, and if the acquired element is still a collection, you can continue to use "/" to get the first element of the collection, sample code:

         Public classStudent { PublicString Name {Get;Set; }  PublicList<book> Books {Get;Set; } }         Public classBook { PublicString BookName {Get;Set; } } List<Student> students =NewList<student>(); Students. ADD (NewStudent () {Name ="Jeff", Books =NewList<book> () {NewBook () {bookname ="C #"},NewBook () {bookname ="Java" } } }); Students. ADD (NewStudent () {Name ="Sam", Books =NewList<book> () {NewBook () {bookname ="Game"},NewBook () {bookname ="Hobbit" } } }); Txtblock1.setbinding (Textblock.textproperty,NewBinding ("/name") {Source = students});//JeffTxtblock2.setbinding (Textblock.textproperty,NewBinding ("/books/bookname") {Source = students});//C #

If the data source itself is the underlying type (such as String, int, and so on), you do not need to specify path and use "." In C # code, and you can either specify the Path property in XAML syntax or you can specify ".".

Several ways to specify a source for a binding

A generic CLR object is used as a data source, and the collection object includes arrays, lists, Observablecollection<t>,ado. NET object, XmlDataProvider, dependent object, control's DataContext property, specifying source through the ElementName property of the binding object, Specify source with the RelativeSource property of the binding, specify the ObjectDataProvider object as source, and use the data retrieved by LINQ as the data source.

When using DataContext as a data source, binding can automatically find the data source to the parent control until a control containing DataContext is found, the Autodiscover process is implemented through dependency properties, and DataContext is a dependency property. The properties of the parent are automatically inherited when the control does not specify DataContext.

When you bind a data source to a ItemsControl control, you only need to assign the data source object to the ItemsSource property, the data source object should be a collection object, and the control will automatically set the binding for the elements in the collection. In order for the ItemsControl object to be notified when the number of elements in the collection changes, the collection object must implement the IObservable interface. Note the collection element must implement the INotifyPropertyChanged interface if you want to be able to notify the binding object when the element property changes in the collection. Observablecollection<t> for the implementation of the IObservable collection.

When using the ADO DataTable object as the ItemsControl data source, the DefaultView property of the DataTable is assigned to ItemsSource. You typically use a ListView to display tabular data, and you need to set the ListView's View property to Gridview,gridview content as gridviewcolumn. The Displaymemberbinding property of Gridviewcolumn is a binding object, which is different from the ListBox by setting the object to specify which property of the source object is associated with that column.

If the XML data needs to be used as the source of the binding, the XmlDataProvider object is required, the XPath setting is used to set the path to the binding, and the @ symbol is used to get the attribute of the XML element, and the child element that is used when the element is taken.

ObjectDataProvider is used to wrap an object that exposes data in a method, specifies the wrapped object by setting the ObjectInstance, MethodName specifies the method to invoke, and methodparameters the parameters of the specified method. When binding ObjectDataProvider to target, you do not need to set the path property of the binding, ObjectDataProvider itself is the data.

Use the RelativeSource of the binding to specify a relative data source, and control the scope and manner in which the binding searches for source through the property settings of the RelativeSource class. The type of the mode attribute is Relativesourcemode, with a value of Previousdata, templatedparent, self, FindAncestor. Instances of RelativeSource can be quickly obtained through static properties Previousdata, TemplatedParent, and self.

Data validation of the binding

The Validationrules property of the

binding is used to control data validation, and multiple checksum objects can be set at the same time. Each validation rule is an ValidationRule object, and ValidationRule is an abstract class that needs to implement its own derived class. The validation of the binding verifies the data from target by default, that is, the data in the default source is always correct, and if you want to verify it when the source is updated, The ValidationRule property needs to be set validatesontargetupdated to true so that the checksum method is also called when the source data is updated. If you want to trigger an event on a validation error, you need to set the NotifyOnValidationError property of the binding to true and listen for the validation error attach event on the target of the binding or on its parent. Example code:

         This New Routedeventhandler (ValidationError));         Private void ValidationError (Object sender,routedeventargs e)        {            if(Validation.geterrors (TEXTBLOCK1). count>0)            {                = validation.geterrors (textBlock1) [0]. Errorcontent.tostring ();            }        }
Data conversion of binding

Type conversion occurs when the value type of the source path property of the binding is inconsistent with the property value type of target. If it is a simple type such as string,double, the conversion method is already built into WPF, and if it is a different complex type, you need to write the transformation class yourself. Implements the IValueConverter interface, which defines two methods that are called when the data flows from the source of the binding to target, whereas the Convertback method is called. The mode of the binding affects how the method is invoked, and if mode is TwoWay, two methods are likely to be called, and if mode is OneWay, only convert is called. Create binding set the converter property of the binding to specify the converter to use for the binding.

MultiBinding

When the information that needs to be displayed in the UI is determined by more than one data source, you need to use a multi-way binding. MultiBinding is the same as binding with BindingBase as the base class, MultiBinding has a property bindings of type BindingBase collection, which brings together multiple binding. Together, the binding determines the data that goes to target multibinding. MultiBinding is sensitive to the order in which subsets of the binding are added, and the order in which they are added determines the order in which the data is passed to converter. The MultiBinding Converter implements the Imultivalueconverter interface, and MultiBinding seems to have to specify a custom converter.

The words binding of the learning notes of the "in Layman's WPF"

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.