Quickly build Windows 8 style apps 25-data binding

Source: Internet
Author: User

Original: Quickly build Windows 8 style apps 25-data binding

This post focuses on how to bind UI elements to data, the direction of data binding, data change notifications, data transformations, and binding scenarios supported by data binding.

Data binding is a simple way to display data, and a connection or binding between a UI element and a data object allows the data to flow between the two. In addition, when the binding is established and the data changes, the corresponding UI element automatically displays the change.

how to bind a UI element to data

As you can see from the diagram above, each binding must specify a source and a target.

Where the source object can be any CLR object, including the target element itself and other UI elements. The target can be any DependencyProperty(dependency property) of the FrameworkElement .

The data binding engine obtains the following from the binding object:

1) Source object and target object;

2) The direction of the data stream;

3) value Converter;

For example, use C # code and XAML to bind the foreground property of a TextBox.

XAML Code:

< TextBox x:name = "MyTextBox" Text = "Text" Foreground = "{Binding Brush1, mode=oneway}" />

C # code:

New MyColors ();
New SolidColorBrush (colors.red);
Mytextbox.datacontext = TextColor;

Binding is using {binding ...} The syntax is created in XAML. The source is set in code by setting the DataContent property of the TextBox.

In addition, the data will be inherited. If we set the data context on a parent element, its child elements will use the same data. We can bind to a property of the source object by setting the Binding.path property.

direction of data binding

Each binding contains a mode property that determines how and when the data flows.

Three types of bindings:

1) OneTime: Binding uses the source data update target when it is created.

2) OneWay: Bindings use source data to update targets (default mode) when they are created and when data changes.

3) TwoWay: The binding updates both the target and the source when any one of the target and source changes.

Data Change Notification

When the source data object is changed, how do you pass the new source data object to the target object? The workaround is to inherit the INotifyPropertyChanged interface from the source data object. Because the inotifypropertychanged interface provides the propertychanged event, the event tells the data binding engine that the source object has changed to make it easier to change the target value.

For example:

Create A class that implements INotifyPropertyChanged.
 Public class Mycolors:inotifypropertychanged
{
    Private SolidColorBrush _brush1;
    Declare the PropertyChanged event.
     Public Event PropertyChangedEventHandler propertychanged;
    Create the property that would be the source of the binding.
     Public SolidColorBrush BRUSH1
    {
        return _brush1; }
        Set
        {
            value;
            
            is updated.
            Notifypropertychanged ("Brush1");
        }
    }
    
    Passing the Source property, which is being updated.
     Public void Notifypropertychanged (string PropertyName)
    {
        if null)
        {
            PropertyChanged ( this
                New PropertyChangedEventArgs (PropertyName));
        }
    }
}

In the sample code, the MyColors class inherits the INotifyPropertyChanged interface, which triggers the PropertyChanged event to notify the target object and changes when the Brush1 property changes.

Data Conversion

When the data we store is displayed in the UI interface, when the user is unfriendly, the data can be displayed in a corresponding conversion. Then we need a converter for the data.

We can set the converter on any binding, and the custom converter class must inherit the implementation of the IValueConverter interface.

For example:

Custom class implements the IValueConverter interface.
 Public class Datetostringconverter:ivalueconverter
{
    #region IValueConverter Members
    
    A month string.
     Public Object Convert (objectvalue
        Object string language)
    {
        Value is the data from the source object.
        DateTime thisdate = (datetime)value;
        int monthnum = thisdate. Month;
        string Month;
        Switch (Monthnum)
        {
             Case 1:
                "January";
                break;
             Case 2:
                "February";
                break;
            default:
                "Month not Found";
                break;
        }
        Return the value to the target.
        return month;
    }
    Convertback is not implemented for a OneWay binding.
     Public Object Convertback (objectvalue
        Object string language)
    {
        Throw New NotImplementedException ();
    }
    #endregion
}

When data is passed from the source object, the binding engine invokes Convert and passes the returned data back to the destination.

When data is passed from the target, the binding engine invokes Convertback and passes the returned data back to the source.

Set converter in XAML code:

< usercontrol.resources >
  < Local:datetostringconverter x:key = "Converter1" />
</ usercontrol.resources >
...
< TextBlock Grid. Column = "0"
  Text = "{Binding Month, Converter={staticresource Converter1}}" />

There are also two optional parameters in the converter:converterlanguage(which allows you to specify the language used in the transformation) and Converterparameter(which allows a parameter to be passed for the conversion logic).

Note: If there is an error in the data conversion, it is best not to throw an exception but return Dependencyproperty.unsetvalue, which will stop the data transfer.

Supported binding Scenarios
Scheme C#
Binding to an Object Can be for any object
Getting property change updates from a bound object The data object must implement the INotifyPropertyChanged interface
Binding to a collection Using List (of T)
Get collection change updates from the binding collection Using ObservableCollection (of T)
Implementing a collection that supports bindings Expand List (of T) or implement IList,IList(belonging to Object),IEnumerable , or IEnumerable (belongs to Object). Operations bound to generic IList (Of T) and IEnumerable (Of T) are not supported
Implementing collections that support collection change updates Extended ObservableCollection (of T) or implemented (non-generic)IList and inotifycollectionchanged
Implementing a collection that supports incremental loading Extend ObservableCollection (of T) or implement (non-generic)IList and inotifycollectionchanged. In addition, isupportincrementalloading is implemented

Note: The form is collated according to the documentation provided by MSDN.

For more information on data binding, refer to:

1. Data binding overview;

2. QuickStart: Data binding to the control;

3. How to bind to hierarchical data and create a master/detail view;

Quickly build Windows 8 style apps 25-data binding

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.