WPF Study Notes 3-Binding

Source: Internet
Author: User

1. Binding: banding is like a bridge between a Source and a target. Data conversion or verification can be performed on the binding process.

1) A source may have multiple attributes, and the attribute to which it is bound is determined by Path. To notify that the property has changed, you must intervene in a PropertyChanged event in the Set statement.

It is easy to implement, as long as this class inherits the INotifyPropertyChanged interface.

Public class ConverterElement: INotifyPropertyChanged
Public event PropertyChangedEventHandler PropertyChanged;
Private double mm;

Public double MM
Get {return mm ;}
Mm = value;
If (this. PropertyChanged! = Null)
PropertyChanged. Invoke (this, new PropertyChangedEventArgs ("Mil "));


2) Implementation of banding

Stu = new Student ();

Binding binding = new Binding ();

Binding. Source = stu;

Binding. Path = new PropertyPath ("Name ");

// Use binding to connect data sources and Binding targets

BindingOperations. SetBinding (this. textboxName, TextBox. TextProperty, binding );

NOTE 1: The BindingOperations. SetBinding method has three parameters: Targe, dependencyProperty of Target, and Binding.

NOTE 2: Because FrameworkElement encapsulates the BindingOperations. SetBinding method, you can bind it as follows:

This. textBoxName. SetBindng (TextBox. TextProperty, new Binding ("Name") {Source = stu = new Student ()});

3) Binding source and Path

  • The control is derived from Binding tag extension as Binding.

Use the following code binding:

Text = "{Binding Path = Value, ElementName = slider1 }"

Or: this. textBox1.SetBinding (TextBox. TextPropety, new Binding ("Value") {ElementName = "slider1 "})

  • Control binding direction and data update

Use Mode to control the data flow: TwoWay, OneWay, OnTime, OneWayToSource and Default.

By default, data is updated only after the control loses focus. How can this problem be implemented in real time?

Using the UpdateSourceTrigger attribute, you can obtain the value PropertyChanged (which can be updated in real time), LostFocus, Explicit, and default.

Note 1) Binding has two bool attributes: NotifyOnSourceUpdated and NotiryOntargetUpdate. If this attribute is set to true, the Binding will trigger the corresponding SourceUpdated event and targetUpdated event after the source or target is updated.

  • Binding Path)

The actual type of Path is PropertyPath.

Path supports multi-level paths: for example, {Binding Path = Text. Length}

You can use the indexer for the collection type: {Binding Path = Text. [3]} or {Binding Path = Text [3]}

When a set or DataView is used as the Binding source, such a syntax is required if we want to use its default element as a Path.

If the attribute of the Set element is still a set, you can continue to slash it.

4) binding without Path

Sometimes, you will see that the Path is a "." Or simply does not. This is because the source is the data, and we want to String and Int. At this time, we only need to set the value of path.

Text = {Binding Path =., Source = {Staticresource ResourceKey = myString }}

Text = {Binding Source = {Staticresource ResourceKey = myString }}

5) several methods for specifying the Source for Binding

  • Specify a single object as Source: If the INotifyPropertyChanged interface is implemented, the Binding data is updated by initiating the PropertyChanged event in the Set statement of the attribute.
  • Specify a common CLR set type object as Source, including an array, List <T>, ObservableCollention <T>
  • ADO. Net data object is specified as source. Including DataTable and DataView
  • Use XmlDataProvider to specify Xml data as Source.
  • Specify the dependency Object as Source: this can be both Source and target.
  • Specify the container's DataContext as the default act of Source (WPF Data Binding ):
  • Use ElementName to specify the Source
  • Specify Source through the RelativeSource attribute of Binding: This method is used when the control needs to focus on its own, and a value of its own container or its internal element.
  • Specify the ObjectDataProvider object as the Source object. When the data of the data Source is not exposed to the outside world through the attribute, you can use this object to wrap the data Source and locate the data Source.
  • Use the Data Object retrieved by Linq as the Binding source

2. Binding without Source-use DataContext as the Binding Source

The DataContext attribute is in the FrameworkElement class, so all WPF controls have the DataContext attribute.

The DataContext attribute is transmitted along the tree.

Note) DataContext is a dependency attribute, which has an important feature: When you do not assign a value to a dependency attribute of the control, the control will "borrow" the property of its container as its own value.

3. Use a collection object as the ItemsSource of the List Control

Use the ItemsSource attribute to carry the IEnumrate set

Use this. ListBoxStudents. DisplayMemberPath = "Name" to specify the Path.

The DispalyMemebrPath attribute will actually pass this value to the Path of ListBoxItem.

Note 1) The Binding creation process is completed in the SelectTemplate method of the DisplayMemberTemplateSelector class.

You can use ItemTemplate to create an itemTemplate.

Note 2) The ObservableCollection <T> is generally used to replace the List <T>, so that the former implements the INotifyCollectionChanged and INotifyPropertyChanged interfaces, and the List control can be immediately notified of the changes in the set.

4. Use the ADO. NET object as the Binding source.

1, DataTable this. listBoxStudents. ItemsSource = dt. DefaultView;

2. Binding to the GridView. The content of the gridview is columns (GridViewColumnCollection). It has a property of DisplayMemberBinding.

3. DataTable cannot be directly used as the Source. However, if you place the DataTable object in the DataContext attribute of an object and associate ItemsSource with a Binding that neither specifies the Source nor the specified Path, binding can automatically find the DefaultView and use it as the Source.

5. Source with XML data as Binding

. Net framwork has two XML data class libraries.

  • Class libraries that comply with DOM standards: including XmlDocument XmlElement XmlNode XmlAttribute and other classes
  • A Class Library Based on Linq. Including XDocument XElement XNode XAttribute and other classes.

Note) When Xml data is used as the Binding Source, we use the XPath attribute instead of the Path attribute to specify the data Source.



<XmlDataProvider XPath = "Student \ Name" x: Key = "xmlProvider">
<X: XData>
<StudentList xmlns = "">
<Student Id = "1"> Tom </Student>
<Student Id = "2"> Jam </Student>
<Student Id = "3"> Dean </Student>
</X: XData>


If it is an attribute, add @ before XPath, and the object does not.

Future code:

XmlDocument doc = new XmlDocument ();

Doc. Load (@ "D: \ RawData. xml ");

XmlDataProvider xdp = new XmlDataProvider ();

// Xdp. Document = doc;

// The Source attribute can also be used here:

Xdp. Source = new Uri (@ "D: \ RawData. xml ")

Xdp. XPath = @ "/StudentList/Student ";

This. listViewStudent. DataContext = xdp;

This. listViewStudent. SetBinding (ListView. ItemsSourceProperty, new Binding ())

2) use TreeView to represent multi-layer xmlsource

Note: HierarchicalDataTemplate has an itemsSource attribute.

For multi-level data, you can use the hierarchicalDataTemplate. ItemTemplate attribute.

6. Use the Linq search result as the binding source

Because the result of Linq inherits from IEnumerable <T>, You can bind ItemsSource directly.

Use the following in XML:

This. ListViewStudent. ItemsSource =

From element in xdoc. Descendants ("Student ")

Where element. Attribute ("Name"). Value. StartWith ("T ")

Selete new Student ()


Id = element. Attribute ("Id"). Value;


7. Use the ObjectDataProvider object as the Binding Source

The parent classes of XmlDataProvider and ObjectDataProvider are both abstract classes of performanceprovider.


ObjectDataProvider odp = new ObjectDataProvider ();

Obp. ObjectInstance = new Calculator ();

Obp. MethodName = "Add ";

Obp. MethodParameters. Add ("100 ");

Obp. MethidParameters. Add ("200 ");

MessageBox. Show (odp. Data. ToString ())';

Use 2:


ObjectDataProvider odp = new ObjectDataProvider ();

Obp. ObjectInstance = new Calculator ();

Obp. MethodName = "Add ";

Obp. MethodParameters. Add ("0 ");

Obp. MethidParameters. Add ("0 ");


// Create a binding for TextBox1

Binding BindingToArg1 = new Binding ("MethodParameter [0]")


Source = odp, BindDirectlyToSource = true, UpdateSourceTrigger = UpdateSourceTrigger. PropertyChanged


// Create a binding for TextBox2

Binding BindingToArg2 = new Binding ("MethodParameter [1]")


Source = odp, BindDirectlyToSource = true, UpdateSourceTrigger = UpdateSourceTrigger. PropertyChanged


// Create a binding for the Result

Binding bindingToresult = new Binding (".") {Source = odp };


This. Textbox1.SetBinding (TextBox. textProperty, bindingToArg1 );

This. Textbox2.SetBinding (TextBox. textProperty, bindingToArg2 );

This. TextboxResult. SetBinding (TextBox. textProperty, bindingToResult ;)


(Note1): BindsDirectlyToSource = true indicates that the Binding object is only responsible for writing the data collected from the UI element to its direct Source, that is, ObjectDataProvider, rather than the Calculator object it wraps.

8. Use the RelativeSource of Binding.

1. If the source of the binding is not clear, for example, to associate a specific data of the current user, uhozhe associates the data of a certain level of container of the current user. In this case, you can consider using the RelativeSource attribute of Binding.

2. Demo:

BindingText using RelativeSource

RelativeSource rs = new relativeSource (RelativeSourceMode. FindAncestor );

Rs. AncestorLevel = 1;

Rs. AncestorType = typeof (Grid );

Binding binding = new Binding ("Name") {RelativeSource = rs };

This. TextBox1.SetBinding (Textbox. TextProperty, binding );

Or use the xaml

Text = {Binding RelativeSource = {RelativeSource FindAncestor, AncestorType = {x: Type Grid}, AncestorLevel = 1}, Path = Name };

3. If TextBox needs to be associated with its own Name attribute, the code should be like this:

Public Window1 ()


RelativeSource rs = new RelativeSource ();

Rs. Mode = RelativeSourceMode. Self;

Binding binding = new Binding ("Name") {RelativeSource = rs };

This. TextBox1.SetBinding (TextBox. TextProperty, binding );


9. Data Conversion and validation by Binding

1. validation: ValidationRule. The custom ValidationRule must inherit the ValidationRule class.

Then implement the ValidationResult Validate (Object value, System. Globalization. CultureInfo cultrueInfo) method.


Binding binding = new Binding ("value") {Source = this. slider1 };

Binding. UpdateSourceTrigger = UpdateSourceTrigger. PropertyChanged;

SelfDefineValidationRule rvr = new SelfDefineValidationRule ();

Rvr. ValidatesOnTargetUpdated = true;

Binding. ValidationRules. Add (rvr); // Multiple Validation class instances can be added here.

(Note1): If data from the Source may also have problems, set the ValidatesOnTargetUpdated attribute of the validation condition to true.

If you want to verify the result, You Can Binding. NotifyOnValidationError = true;

This. textBox1.AddHandler (Validation. ErrorEvent, new RoutedEventHandler (this. ValidationError ));

This. textBox1.ToolTip = Validation. GetErrors (this. textBox1) [0]. ErrorContent. Tostring ();

2. Data Conversion inherits from IvalueConverter

Public interface IValueConverter

Object Convert (object value, Type targetType, object Parameter, CultureInfo culture );

How to use it?

<Local: CategoryToSourceConverter x: Key = "cts"/>

Text = {Binding Path = Category, Converter = {StaticeResource ets }}

9. MultiBinding)

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.