Data bindings for Windows Phone 7)

Source: Internet
Author: User

I have been familiar with data binding for ASP. NET or Silverlight, WP7 is based on Silverlight, And the Silverlight for Windows Phone page also uses XAML, so the page rendering principle is the same.

Data Binding is divided into source and target. Source is generally divided into two types: data sources of other controls or data objects.

Let's talk about using controls as the data source. The simplest format is: target control property = "{binding elementname = source control name, Path = source control property }".

To facilitate converter introduction, I gave up using textbox as the data source, instead of using silvder, so that some children's shoes may be wrong.

Place a silder and a textblock on the page. The XAML code is as follows:

Slider Height="84" HorizontalAlignment="Right" Margin="0,41,0,0" Name="MySilder" Value="20" Minimum="0" Maximum="100" VerticalAlignment="Top" Width="450" /><TextBlock Height="30" HorizontalAlignment="Left" Margin="30,163,0,0" Name="TargetTB" Text="{Binding ElementName=MySilder, Path=Value}" VerticalAlignment="Top" />

In the code, the text attribute value of textblock is bound, the source is silder, and the bound attribute is value, which means the value of the text attribute of textblock, value from the value attribute of silider
Run the program and drag the silder line. The effect is as follows:

As you can see, the text value of textblock also changes when you drag the silder. The binding mode of the binding mode is related. The default mode of binding is oneway, and the binding mode is single, that is, when the value of the silder changes, the text of textblock will change, but the value of silder will not change when the text of textblock changes. There are two other types: onetime and twoway, and onetime is the binding order, that is, the text of textblock gets the first value of the silder. When the value of the silder changes again, the text of the textblock will not change. Twoway is bidirectional binding, that is, changing the value of the silder, and changing the text of the textblock, the value of the silder will also change. In the converter effect, the example is not provided for the moment.

Converter is used for data conversion. For example, if I want the source data, but the source data format is not what I want, so I can use converter to get the value that I want to display. converter only changes the value displayed on the page. It is not expensive to change the value of the source data.

The converter implementation method is to define an inherited ivalueconverter interface and implement the convert and convertback methods. Now we add a class in the project. The Code is as follows:

Public class valueconverter: ivalueconverter {public object convert (object value, type targettype, object parameter, cultureinfo culture) {string strvalue = ""; double doublevalue = (double) value; if (doublevalue> 50) strvalue = "The obtained value is relatively large"; else strvalue = "The obtained value is relatively small"; return strvalue;} public object convertback (object value, type targettype, object parameter, cultureinfo culture) {return value ;}}

Then add the class to static resources for use. In app. XAML, add the namespace: xmlns: Local = "CLR-namespace: databindings" in the current project"

Then declare the valueconverter class as a static resource: <local: valueconverter X: Key = "valueconverter"/>

Modify mainpage. text Content of textblock in XAML: <textblock Height = "30" horizontalalignment = "Left" margin = "30,163, 0, 0 "name =" targettb "text =" {binding elementname = mysilder, Path = value, mode = twoway, converter = {staticresource valueconverter} "verticalignment =" TOP "/>.

The binding mode has been set to twoway, so we can use the code to modify the text attribute value of textblock to see if silder is changing.

Add a code in page_loaded mode to modify the text attribute value of textblock after page initialization: targettb. Text = "40 ";
Run the project as follows:

I didn't set the text value of textblock to 40 in the page_loaded method, and I saw that the value of silder has changed to 40, proving that mode = twoway works. I can see that the text value of textblock is not 40, instead, "the obtained value is relatively small" to prove that our valueconverter is working. Drag the silder to make its value greater than 50%. We should guess the text value of textblock, it should be "The obtained value is relatively large" to see if the effect is correct.

Next, let's talk about how to use more data objects as data sources in actual development.

First, add a datasource and person class to provide the data source. The Code is as follows:

Public class datasource {private person _ persondata; public person persondata {get {return _ persondata;} set {_ persondata = value ;}} public datasource () {persondata = new person () {name = "DHC", sex = "male", age = 27 };}} public class person: inotifypropertychanged {private string _ name; public string name {get {return _ name;} set {_ name = value;} private string _ sex; Public String sex {get {return _ sex ;} set {_ sex = value ;}} private int _ age; Public int age {get {return _ age ;}set {_ age = value ;}}}

Then set the data source for the mainpage

DataSource ds = new DataSource();DataContext = ds.PersonData;

Add three textblocks on the mainpage. XAML page and bind the data.

<TextBlock Text="{Binding Name}"/><TextBlock Text="{Binding Sex}"/><TextBlock Text="{Binding Age}"/>

Run the program as follows:

Datacontext is used above, and datacontext is the data content. The data source on the entire page set above has the datacontext attribute in almost any space, its own attributes or the attributes of the sub-control can be bound to the attribute values of the data source object. After the datacontext of the parent control is set, the datacontext attribute of all child controls is the same as that of the parent control by default, unless the child control sets its own datacontext.

The binding format is similar: {binding source = data source, Path = property name} As for mode and converter, the usage is the same as that of the control described above. The default value of source is datacontext. Unless not, It is omitted and not written. The path keyword is omitted. Therefore, the simplest format is {binding attribute name }.

Let's change the data to see if the text of textblock has changed.

Add a button on the page and add code in the Click Event

Person person = DataContext as Person;person.Age = 100;

Run and click. The effect is as follows:

Age does not change to 100. This is not the result we want. Why?

Inotifypropertychanged Interface

The above program, click the button, does not show the text of the textblock of age as we imagined, because after the data changes, the UI interface is not notified, why is there no notification after the value of the silder is changed, because the person class defined above does not inherit the inotifypropertychanged, and the interface name is displayed, he knows what he is doing, and notifies him of attribute changes.

The usage is to directly inherit inotifypropertychanged, use propertychangedeventhandler to add a delegate, and the notification data has changed. Now the person class is modified.

public class Person: INotifyPropertyChanged    {        public event PropertyChangedEventHandler PropertyChanged;        protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)         {             if (PropertyChanged != null)                 PropertyChanged(this, args);         }        private string _name;        public string Name        {            get            {                return _name;            }            set            {                _name = value;                OnPropertyChanged(new PropertyChangedEventArgs("Name"));            }        }        private string _sex;        public string Sex        {            get            {                return _sex;            }            set            {                _sex = value;                OnPropertyChanged(new PropertyChangedEventArgs("Sex"));            }        }        private int _age;        public int Age        {            get            {                return _age;            }            set            {                _age = value;                OnPropertyChanged(new PropertyChangedEventArgs("Age"));            }        }    }

Run the program again and click the button. The effect is as follows:

Okay, that's what we want.

At the end, we can declare the data as a static resource, and then bind

Declare static resources: <local: datasource X: Key = "data"/>

Set the data source for the page: datacontext = "{staticresource data }"

Bind data to control properties

<TextBlock Text="{Binding PersonData.Name}"/><TextBlock Text="{Binding PersonData.Sex}"/><TextBlock Text="{Binding PersonData.Age}"/>

The running effect is the same as above. The reason why I leave it to the end to bind static resources is that if the data source that does not inherit the inotifypropertychanged interface is declared as a static resource, there is no data on the page after the binding, this is because we write the datasource class in a reasonable way and initialize the data in the constructor. In this way, when declaring an attribute, no value is assigned (null ), however, because the inotifypropertychanged interface is not inherited in the constructor, the UI data is not notified to be changed (or null), which cannot be displayed. We need to rewrite datasource, assign a value to the persondata variable so that it can be displayed. However, this is not a good way to write the variable, and the get and set attribute accessors are used to make the code ugly, if I do not explain, my current code is used by my shoes, and the data cannot be displayed, I should be scolded. So after I finish inotifypropertychanged, I am talking about binding static resources, if you inherit inotifypropertychanged, you will not be asked. Question.

 

 

Related Article

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.