WP8.1 Study5:data binding Data bindings

Source: Internet
Author: User

First, data binding

The simplest way to program UI controls is to write your own data to get and set the properties of the control, e.g. TextBox1.Text = "Hello, world"; But in complex applications, such code can quickly become clumsy and error-prone.

Therefore, to be more convenient, use XAML data binding to your UI to link to a class that contains the application's data in the application.

    • This class is a data source for data binding (ViewModel) that is called a view model.
    • The UI control can automatically get its display value from the properties of the view model ViewModel class, and the control display can be updated by changing the ViewModel property.

    • The user's input can automatically update the view model's binding properties for the ViewModel class.

1. DataBinding data Binding in XAML

As an example:

<x:name= "Directionstextblock"  textwrapping= "Wrap"             Margin= "12,0,0,0"  Text= "{Binding directions}"/> 

In the example above, the Text property of TextBlock is bound to the attributes of some data sources. So what can we do to define the data source? Here are two methods:

    • Datacontext: The Datacontext property of any FrameworkElement derived class (can be set directly in the control, but is usually set in a container type of control, such as a grid, or directly on a page)
    • Itemsource: The Itemsource property of some list controls.

2. Data binding mode modes

As an example:

<x:name= "Directionstextblock"  textwrapping= "Wrap"              Margin= "12,0,0,0"  Text= "{Binding directions, mode=oneway}"  />

The Mode property determines how synchronization between the target control and the data source is changed

    • After the onetime--control property is set, any subsequent changes after the data value are ignored
    • oneway--data object changes can be synchronized to control properties, but not vice versa
    • TwoWay--Variable data objects are control properties that can be synchronized, or vice versa.

3, INotifyPropertyChanged

Objects are set to OneWay or TwoWay bindings must implement the INotifyPropertyChanged interface.

We can write the following code in the ViewModel class:

 Public classitemviewmodel:inotifypropertychanged{Private string_id; ///Sample ViewModel property;     Public stringID {Get{return_id;} Set {            if(Value! =_id) {_id=value; Notifypropertychanged ("ID"); }        }     }     Public EventPropertyChangedEventHandler propertychanged; Private voidnotifypropertychanged (String PropertyName) {PropertyChangedEventHandler handler=propertychanged; if(NULL!=handler) Handler ( This,NewPropertyChangedEventArgs (PropertyName)); }}

There is a better way to do this, and it is interesting to consult the relevant information.

4. Data binding to list binding to Lists

<x:name= "Ingredientslistbox"            ItemTemplate= "{ StaticResource mydatatemplate}"            DataContext="{StaticResource Recipeviewmodel}"/>            itemssource=" {Binding ingredients} "/>

In this example, DataContext is a Recipeviewmodel object, and ItemsSource is bound to an object named ingredients, which is a collection of objects. However, if you want your UI to be automatically updated when the subproject is added or deleted, the data source should be a observablecollection<t> (inotifycollectionchanged is implemented), And the projects in the collection need to implement INotifyPropertyChanged. is like:

 Public classrecipedetails:inotifypropertychanged {/// <summary>     ///A collection for Itemviewmodel objects. /// </summary>      PublicObservablecollection<itemviewmodel> Items {Get;Private Set; }  Public voidLoadData () { This. Items.Add (NewItemviewmodel () {ID ="0", Lineone ="Runtime One", Linetwo = ... });  This. Items.Add (NewItemviewmodel () {ID ="1", Lineone ="Runtime", Linetwo = ... });  This. Items.Add (NewItemviewmodel () {ID ="2", Lineone ="Runtime three", Linetwo =...}); }          ...}

5. Improved data binding: Fallbackvalue and Targetnullvalue

Targetnullvalue allows you to specify properties that are displayed when an override property or value is returned when a property of the specified data source returns NULL.

<Content= "{Binding path=nextitem, Mode=oneway,         targetnullvalue={ Binding Path=nullvalue}}"/>

Fallbackvalue allows you to specify an alternative attribute or value display when you are bound to a property that does not exist.

<Text= "{Binding path=badpath,            fallbackvalue= ' This is a fallback value '}  "                grid.column=" 1 "></TextBlock  >

WP8.1 Study5:data binding Data bindings

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.