WPF data binding (1-simple data binding)

Source: Internet
Author: User
ArticleDirectory
    • Simple data binding

 

(Special statement: oreilly was found in the process of learning WPF. programming. wpf.2nd. edition. the data binding part of aug.2007 is very good, so it is organized in the form of notes for your reference,In case of any copyright dispute, please contact me and I will immediately withdraw this article from cnblogs and apologize)

//************************************** **********************

Recommended WPF books:

1. Do not be blinded by the hype of book dealers. The Chinese Translation of "WPF secrets" has been praised as a classic. In fact, I think this book is just a simple taste, and not detailed enough is its most critical weakness.

2. WPFProgramDesign Guide APP = code + markup is a good book. You can also learn a lot of development skills carefully, but the books separate code from markup. if you can

It will be more popular to combine and carefully organize the content chapter.

3. "Pro WPF in C #2008 Windows Presentation Foundation with. Net 3.5 Second Edition" is a good book,

In my opinion, unlike oreilly. Programming. wpf.2nd. Edition. aug.2007, the two books explain the WPF content in great detail and set chapters reasonably.

It is suitable for quick understanding of WPF development knowledge and is the first choice for learning WPF.

4. As for other books, you may be wise and wise. As for a Chinese WPF programming book in the bookstore, I don't want to talk about it, but I suggest renaming it "simple understanding of WPF" may be more reasonable.

5. There are thousands of books, each with its own characteristics. There are not many excellent books made in computer programming. If new technologies are not used in the market for three years, we recommend that you use foreign books first,

I hope that this sentence will not make some people unhappy. In fact, if you want to refute it, please stand up like Bruce Lee and show you a set of good boxing skills.

 

//************************************** **********************

 

Data Binding is the process of associating various data with the user display control. The Data Binding Mechanism of WPF can be minimalCodeThis association is easy to process.

Simple data binding 1 no data binding

When implementing such user interaction:

 

No data binding mechanism is required.

This. nametextbox. Text = person. Name;

This. agetextbox. Text = person. Age. tostring ();

In this way, once the data changes, the interface value is written back to the person object.

1.1 object changes

How can we synchronize the UI reality with changes when the object changes?

The implementation is still complicated. You can see the following code.

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. componentmodel; // inotifypropertychanged

Namespace simpledatabinding
{
Class person: inotifypropertychanged
{
Public event propertychangedeventhandler propertychanged;
Protected void notify (string propname)
{
If (this. propertychanged! = NULL)
{
Propertychanged (this, new propertychangedeventargs (propname ));
}
}

Public Person ()
{
_ Age = 0;
_ Name = "null ";
}

Private string _ name;
Public string name
{
Get
{Return _ name ;}
Set
{
If (value = _ name)
{Return ;}
_ Name = value; // Note: you cannot use this. Name to assign values. If this creates a loop call, stack overflow occurs.
Y ("name ");
}
}

Private int _ age;
Public int age
{
Get
{Return _ age ;}
Set
{
If (value = _ age) return;
_ Age = value;
Y ("Age ");
}
}

}
}

Using system;
Using system. Collections. Generic;
Using system. LINQ;
Using system. text;
Using system. windows;
Using system. Windows. controls;
Using system. Windows. Data;
Using system. Windows. documents;
Using system. Windows. input;
Using system. Windows. Media;
Using system. Windows. Media. imaging;
Using system. Windows. Navigation;
Using system. Windows. shapes;
Using system. componentmodel;

Namespace simpledatabinding
{
/// <Summary>
/// Interaction logic of window1.xaml
/// </Summary>
Public partial class withoutdatabinding: Window
{
Private person _ person;

Public withoutdatabinding ()
{
Initializecomponent ();

// The following object can be used for initialization. However, in this example, no value is assigned to the user to change the UI using attributes.
// _ Person = new person
//{
// Name = "zhangying ",
// Age = 28
//};
_ Person = new person ();

_ Person. propertychanged + = delegate (Object sender, propertychangedeventargs E)
{
Switch (E. propertyname)
{
Case "name ":
This.txt _ name. Text = _ person. Name;
Break;
Case "Age ":
This.txt _ age. Text = _ person. Age. tostring ();
Break;

}
};

}

Private void button2_click (Object sender, routedeventargs E)
{
_ Person. Name = "zhangying ";
_ Person. Age = 28;
}

}
}

1.2 UI changes

When the UI input value changes, how does one synchronize the object value? You need to set the Event code for them:

Private void txt_name_textchanged (Object sender, textchangedeventargs E)

{

_ Person. Name = this.txt _ name. text;

}

Private void txt_age_textchanged (Object sender, textchangedeventargs E)

{

Int age = 0;

If(int.tryparse(this.txt _ age. Text, out age)

{

_ Person. Age = age;

}

}

2. Data Binding

The preceding example uses manual means to synchronize the Object Attributes With the UI display, while the WPF Data Binding registers two attributes with the Data Binding engine for synchronization and suitable data conversion, for example:

2.1 bindings

1. bind with element attributes:

<Textbox>

<Textbox. Text>

<Binding Path = "Age"/>

</Textbox. Text>

</Textbox>

2. Simplified property binding

<Textbox text = "{binding Path = age}"/>

Simplified mode:

<Textbox text = "{binding age}"/>

Let's look at the binding method of more features (the method of attribute elements ):

<Textbox>

<Textbox. Foreground>

<Binding Path = "Age" mode = "oneway" Source = "{staticresource Tom }"

Converter = "{staticresource ageconverter}"/>

</Textbox. Foreground>

</Textbox>

The binding method above can be as follows:

Foreground = "{binding Path = age, mode = oneway, source = {staticresource Tom },

Converter = {staticresource ageconverter} "/>

Note the usage of quotation marks and the use of quotation marks without quotation marks. Attribute elements must be used in quotation marks.

The following chart lists the attributes that may be used when bound to an object:

These attributes will be described later.

2.2 implicit Data Source

In WPF, each frameworkelement and frameworkcontentelement object has a datacontex attribute, which is of the object type, so you can specify any type of value for it. When we define an object as the binding object, the binding engine searches for the database binding source in the logic tree, as shown in:

2.3 Data island Data Islands

You can see the following sample code:

Private void btn_click (Object sender, routedeventargs E)

{

Person = (person) This. findresource ("ZY ");

MessageBox. Show (string. Format ("I am {0}, age is {1}", person. Name, person. Age. tostring ()));

}

2.4 show data source explicit data source

Displaying Data Source settings is very important for multiple data sources. We can bind the Attribute source.

Note that attributes of different data sources are set in the preceding two text boxes.

2.5 bind to another control binding to other controls

The following code is used:

<Grid>

<Slider name = "slider1"/>

<Textblock text = "{binding Path = value, elementname = slider1}"/>

</GRID>

2.6 value conversion value conversation

In the above Code, we found that the binding is to bind a numeric type to a string, and the type does not match. How does this happen? It turns out that this is a credit for the value converter class. It implements the ivalueconverter interface, which has two methods: Convert and convertback. (This interface is in the system. windows. data namespace, presentationframework. DLL assembly), when implementing the ivalueconverter interface, it is best to use the valueconversionattribute to modify this implementation, so as to instruct the development tool to convert the involved data type, the following example shows: (The following example is excerpted from msdn)

See the following usage:

Use method: Specify the data source first

2.7 editable value conversion2.8 Validation

A verification rule is a piece of data verification code when a target data updates the source data. This Code generally inherits the validationrule class and overwrites the validate method. A built-in rule is called exceptionvalidationrule.

The following code shows the most basic verification method:

When we run the program

The data format in the input box is incorrect when the red border is displayed. However, we found that this was still unfriendly because there was no message indicating why the error was correct.

To display errors, you need to use the Bound event to listen for validationerror. The code example can easily describe this:

This is not the case yet. It must also be set as follows:

We certainly understand the running results. Of course, this may not be what we need. We can control behavior more, which requires us to customize verification rules. Next we will use an example to illustrate the custom verification rules.

First, we inherit the validationrule class and then override the validate method. Let the Code explain everything:

In actual projects, you may not like the error prompt dialog box very much. The best way is to use the tooltip for Windows form verification, however, it is worth noting that validaterule does not have a tooltip similar to the validatesucess event, which makes the display of the entire tooltip very strange.

2.9 binding path syntax

The descriptions on msdn are listed below:

You can use the path attribute to specify the source value to bind:

· In the simplest case, the path attribute value is the attribute name of the source object to be bound, such as Path = propertyname.

· In C #, you can use similar syntax to specify the sub-attributes of an attribute. For example, the Path = shoppingcart. ORDER clause is bound to the order subattribute of the object or shoppingcart.

· To bind an additional Property, parentheses should be placed around the additional property. For example, to bind to the additional property dockpanel...:. Dock, the syntax is Path = (dockpanel. Dock ).

· You can specify the property indexer in square brackets after the property name of the indexer to be applied. For example, the clause Path = shoppingcart [0] sets the binding as an index corresponding to the internal index of the attribute to process the text string "0. Nested indexers are also supported.

· You can mix the indexer and sub-attributes in the path clause. For example, Path = shoppingcart. shippinginfo [mailingaddress, street].

· Within the indexer, You can have multiple indexer parameters separated by commas. You can use parentheses to specify the type of each parameter. For example, you can have Path = "[(SYS: int32) 42, (SYS: int32) 24]", where sys maps to the system namespace.

· If the source is a collection view, you can use a slash (/) to specify the current item. For example, the clause Path =/is used to set the binding of the current item to the view. If the source is set, this syntax specifies the current item of the default set view.

· You can use Attribute names and slashes to traverse the attributes of a set. For example, Path =/offices/managername specifies the current item of the source set, which also serves as the offices attribute of the set. The current item is an object that contains the managername attribute.

· You can also bind a period (.) path to the current source. For example, text = "{binding}" is equivalent to text = "{binding Path = .}".

Escape Mechanism

· In The indexer ([]), the insert symbol (^) is used to escape the next character.

· If you set path in XAML, you also need to use the XAML entity to escape certain characters dedicated to the XAML analysis program:

· Use & amp; to escape the character.

· Use & gt; to escape the end mark ">.

· If you use the markup extension syntax to describe the entire binding in the property, you need to use the backslash \ to escape characters specific to the WPF markup Extension Analysis Program:

· The backslash \ itself is an escape character.

· Equal sign (=) separates attribute names from attribute values.

· Comma (,) is used to separate attributes.

· The right braces (}) indicate the end of the extension.

Binding The tooltip property to the validation error message

<Textbox

Name = "agetextbox "...

Tooltip = "{binding

Elementname = agetextbox,

Path = (validation. Errors) [0]. errorcontent} ">

<Textbox. Text>

<Binding Path = "Age">

<! -- No need for processing yonvalidationerror = "true" -->

<Binding. validationrules>

<Local: numberrangerule min = "0" max = "128"/>

</Binding. validationrules>

</Binding>

</Textbox. Text>

</Textbox>

2.10 relative data source relative Source

Or code to explain how easy to understand

<Textbox...

Tooltip = "{bindingRelativesource = {relativesource self },

Path = (validation. Errors) [0]. errorcontent} ">

In the above example, we use the elementname = txtdate method to specify the object. Here we use self to represent the object generated by referencing the element where the tag is located. Of course, we can also use parent to point to the upper level, the relative resource will be discussed in subsequent chapters.

2.11 Update source trigger

Previously, we basically verified and updated the data source when the target control loses focus. In fact, there are multiple types of data source update mechanisms, as shown below:

Namespace system. Windows. Data

{

Public Enum updatesourcetrigger

{

Default = 0, // updates "naturally" based on the target control

Propertychanged = 1, // updates the source immediately

Lostfocus = 2, // updates the source when focus changes

Explicit = 3, // must call bindingexpression. updatesource ()

}

}

The following declaration must be made in XAML:

<Binding Path = "Age" updatesourcetrigger = "propertychanged">

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.