[Win8] Windows 8 Development notes (8): Basics of Data Binding

Source: Internet
Author: User
Tags blank page

Use the simplest example to demonstrate data binding.

Create a project named testdata and drag two controls to the screen: textbox and slider.

Set slider name to slider1, and then add data binding between the two controls so that the textbox always displays the progress value in the slider.

Then add data binding to the text attribute and specify the object as slider1. The complete code is as follows:

 <Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">        <TextBox HorizontalAlignment="Center" Margin="0,-100,0,0" TextWrapping="Wrap"                  Text="{Binding Value, Mode=TwoWay, ElementName=slider1}" VerticalAlignment="Center"/>        <Slider x:Name="slider1" HorizontalAlignment="Center" VerticalAlignment="Center" Width="200" Height="30"/>    </Grid>

The result of running is 1. The value of the text box also changes when the slider is dragged. 2. the scroll bar also changes when the content of the text box is changed. This is twoway:


So how can I write data binding on my own?

Create a person class to test.

using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;namespace TestData{    class Person    {        public string Name        {            get;            set;        }        public int Age        {            get;            set;        }    }}

Drag a textbox and two buttons on the home page. One button is used to read the person value, and the other is used to modify the person value:


Name textbox text1 for later use.

Double-click the read button to jump to the C # file in the background.

Declare a person object in the class: person myperson = new person ();

Then, in the onnavigatedto method, if it is navigationmode. New, set the datacontent of text1 to the previously declared myperson.

Datacontent can be understood as a data source.

Then, click the monitoring method of the button to display the read person content. When you click the second button, the person name is displayed as the current millisecond value.

The complete code is as follows:

Using system; using system. collections. generic; using system. io; using system. LINQ; using Windows. foundation; using Windows. foundation. collections; using Windows. UI. popups; using Windows. UI. XAML; using Windows. UI. XAML. controls; using Windows. UI. XAML. controls. primitives; using Windows. UI. XAML. data; using Windows. UI. XAML. input; using Windows. UI. XAML. media; using Windows. UI. XAML. navigation; // blank page item template in http://go.m Icrosoft.com/fwlink /? Linkid = 234238 introduces namespace testdata {// <summary> /// you can use it to navigate to a blank page inside the frame. /// </Summary> Public sealed partial class mainpage: Page {person myperson = new person () {name = "why", age = 20}; Public mainpage () {This. initializecomponent () ;}/// <summary> /// call when this page is to be displayed in the frame. /// </Summary> /// <Param name = "E"> describes how to access event data on this page. Parameter // properties are usually used on the configuration page. </Param> protected override void onnavigatedto (navigationeventargs e) {If (E. navigationmode = navigationmode. new) {text1.datacontext = myperson;} private void button_click_1 (Object sender, routedeventargs e) {messagedialog mydialog = new messagedialog (myperson. name); mydialog. showasync ();} private void button_click_2 (Object sender, routedeventargs e) {myperson. name = datetime. now. millisecond. tostring ();}}}

Then, set the textbox data binding on the XAML page and bind it to the name attribute of the data source (the data source set earlier ):

The complete XAML code is as follows:

<Page X: class = "testdata. mainpage "xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "xmlns: Local =" using: testdata "xmlns: D =" http://schemas.microsoft.com/expression/blend/2008 "xmlns: MC =" http://schemas.openxmlformats.org/markup-compatibility/2006 "MC: ignorable = "D"> <grid background = "{staticresource applicationpagebackgroundthemebrush}"> <textbox X: Name = "text1" horizontalalignment = "center" margin = "0, 0, 0 "textwrapping =" Wrap "text =" {binding name} "verticalignment =" center "/> <button content =" read "horizontalalignment =" center "margin =" 0, -0,100, 0, 0 "verticalignment =" center "Click =" button_click_1 "/> <button content =" change "horizontalalignment =" center "margin =, 0, 0 "verticalignment =" center "Click =" button_click_2 "/> </GRID> </Page>

When running the project, it is found that why is displayed, but the value in textbox does not change after you click Modify, because the text does not know that it has changed.

So how do I know immediately when the name changes?

We need to modify the person class.

In data binding, we recommend that you implement an inotifypropertychanged interface.

It has only one member, that is, the propertychanged event.

Make a slight modification to set. The complete person. CS file is as follows:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Linq;using System.Text;using System.Threading.Tasks;namespace TestData{    class Person : INotifyPropertyChanged    {        private string _name;        public string Name        {            get            {                return _name;            }            set            {                _name = value;                if (PropertyChanged != null)                {                    PropertyChanged(this, new PropertyChangedEventArgs("Name"));                }            }        }        private int _age;        public int Age        {            get            {                return _age;            }            set            {                _age = value;                if (PropertyChanged != null)                {                    PropertyChanged(this, new PropertyChangedEventArgs("Age"));                }            }        }        public event PropertyChangedEventHandler PropertyChanged;    }}

Run again. When you click Modify, the textbox changes accordingly.



By the way, there are three binding modes,

  • Onetime: one-time binding
  • Oneway: one-way binding
  • Twoway: bidirectional binding
The child control inherits the bound data of the parent control by default. This is the concept of data context. For example, the binding data source mentioned above can also be written as: This. datacontext = myperson;

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.