[UWP Development] data binding those things (2)

Source: Internet
Author: User

Then the last article to Kan.

Two. Binding between entities to controls

It is not known here that the word "entity" is just inappropriate, and that you can live to understand it. He can be an instance of a class, or it can be a collection.

So, the corresponding we introduced two demo, the first introduction of a simple class as a data source, the second introduces a collection as a data source

Not much nonsense to say, to see the demo, I first on the code, after the analysis

DEMO1:

XAML page

<page.resources>        <Local:userx:key= "User"></Local:user>    </page.resources>    <Grid>        <StackPanelDataContext="{StaticResource User}"HorizontalAlignment= "Center">            <TextBlockx:name= "Tbid"Text="{Binding Path=id}"></TextBlock>            <TextBlockx:name= "Tbname"Text="{Binding Path=name}"></TextBlock>            <TextBlockx:name= "Tbgender"Text="{Binding Path=gender}"></TextBlock>        </StackPanel>    </Grid>

  

User class:

 Public class User    {        publicint id{get;  Set}        publicstring name{get;  Set}        publicstring gender{get;  Set;}    }

C # code:

 Public Sealed Partial classMypage:page { PublicMyPage () { This. InitializeComponent ();
User User=resources["User"] asUser; if(User! =NULL) {user.id=10000; User. Name="CQ"; User. Gender="Unknown"; } } }

The above two are all the code, here I say the implementation of the approximate process.

When executing the constructor of the MyPage class, we get the instance of the user class of the static resource defined on the MyPage page through the user user=resources["user" as user, then assign the value, run the program, we find that the control is displayed on the

We value the data.

In fact, we defined three TextBlock controls in XAML to display three properties in the user class, but we only declared path in their binding and did not specify ElementName, which is the data source, when they looked for their parent

The data source for the element, which must contain Id,user,gender three properties. The attribute DataContext (data context) is defined in their parent element StackPanel, and it indicates the data source here, who is it? Is "user", which is defined in the static

The resource. Then in the constructor of the MyPage class, we get the instance of the class user, assigning him the value, finally through the data binding technology, they finally display on the screen! Note: When they are displayed, if the property values in the user class are modified artificially, this change is

is not displayed on the interface. What if you want it to change? Look down!

  In the DEMO1 code is actually no practical use, want to have the use, we transform it!!!

Previously, we needed to make the changed data appear on the interface after the property value of the user class instance changed. So make the following changes! Just change the user class to do it!

  

 Public classuser:inotifypropertychanged {Private int_id; Private string_name; Private string_gender;  Public intID {Get            {                return_id; }            Set{_id=value;            OnPropertyChanged (); }        }         Public stringName {Get            {                return_name; }            Set{_name=value;            OnPropertyChanged (); }        }         Public stringGender {Get            {                return_gender; }            Set{_gender=value;            OnPropertyChanged (); }        }         Public EventPropertyChangedEventHandler propertychanged;  Public voidOnPropertyChanged ([Callermembername]stringPropertyname="")        {            if(PropertyChanged! =NULL) {propertychanged ( This,NewPropertyChangedEventArgs (PropertyName)); }        }    }

In fact, understanding is still relatively simple. Imagine, provide a mechanism, after the user property changes, the notification system said "My value has changed, you have to give me the interface to express again", then this mechanism by let user inherit inotifypropertychanged this

interface to implement.

In contrast to this class and previous, in addition to implementing the interface INotifyPropertyChanged interface, but also defined a public method onpropertychanged, followed by all the properties of the Set method Riga OnPropertyChanged () method, Used to inform

The property value has changed.

Tip tip: The role of the Callermembername feature is to call the OnPropertyChanged method, the name of the property as a parameter to enter, if not added, the call will need to manually enter the property name, so the probability of error is relatively large!

The true internal principle of inotifypropertychanged, please MSDN!... In fact, I don't quite understand!

Well, do the above modification, is the first we need the function!

DEMO2

Let's play a useful one this time. Data in a collection is bound to a list!

First on the code!!!

Xaml:

<StackPanel>            <ButtonContent= "Change"Click= "Button_Click"></Button>            <ItemsControlx:name= "ItemsControl"ItemsSource="{Binding}">                <itemscontrol.itemtemplate>                    <DataTemplate>                        <StackPanelOrientation= "Horizontal">                            <TextBlockText="{Binding Id,mode=oneway}"/>                            <TextBlockText="{Binding Name,mode=oneway}" ></TextBlock>                        </StackPanel>                    </DataTemplate>                                   </itemscontrol.itemtemplate>            </ItemsControl>        </StackPanel>

Product

 Public classProduct {Private int_id; Private string_name;  Public intID {Get{return_id;} Set{_id=value; }        }         Public stringName {Get{return_name;} Set{_name=value; }        }    }

C#:

  

 Public Sealed Partial classMypage:page {List<Product> list =NULL;  PublicMyPage () { This.            InitializeComponent (); List=NewList<product>            {                NewProduct {id=1, name="potatoes" },                Newproduct{id=2, name="Potato"},                Newproduct{id=3, name="Potato"}                           }; Itemscontrol.itemssource=list; }        Private voidButton_Click (Objectsender, RoutedEventArgs e) {            if(List! =NULL) {list. ADD (NewProduct {ID =4, Name ="Potato" }); }        }    }

  

This is the result of the operation. Don't mind the "change" button first.

This time a ItemsControl list control is defined and a template is defined for its ItemTemplate , knowledge or data binding. I don't know, I can read this article datatemplate and ControlTemplate contact and difference

Then define a generic collection list<product>, after adding three data, set it to ItemsControl data source, note that there is no DataContext settings, with the Itemsource property! (And this difference can Baidu!) )

After running the program, the discovery data has been successfully displayed on the interface.

Here, it has been implemented how to display the data in a collection in a list control!

  The role of the "Change" button is to add a list of data, but after the click, the interface does not respond, but through debugging found that the data is indeed added to the list, knowledge is not displayed, combined with our previous blog post,

it should be possible to guess that there is a lack of a notification mechanism. when we change the list<product> to observablecollection<product> , we will find that we can change the data.

By viewing the definition Discovery observablecollection<t> implements the interface inotifycollectionchanged, INotifyPropertyChanged, It is these two interfaces that provide this notification mechanism!

So far. I'm done with my experience. But the total feeling is not enough to say, not clear. I'll talk about some of the tips in the post.

  

[UWP Development] data binding those things (2)

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.