WPF binding instance details

  • 2020-09-16 07:45:41
  • OfStack

This article describes the usage of WPF binding in detail and shares it with you for your reference. Specific usage analysis is as follows:

1. The source property used by the WPF binding must be a dependency property because the dependency property has built-in support for change notification, the element binding expression USES the Xaml extension tag, WPF binds 1 control using Binding.ElementName, and Source,RelativeSource,DataContext (WPF only, not XAML) for non-control objects, and can only bind to common fields of the object.
Here are some Binding attribute names, a complete list of references: http: / / msdn microsoft. com/zh - cn library/vstudio/ms750413 aspx

Source: data provider
RelativeSource: Based on the current object, it automatically finds the source and binds
DataContext: If you do not use Source and RelativeSource,WPF will start from the current control in the control tree to look up, and use the first non-empty DataContext property, you can set DataContext on a higher level container object, Text is bound to Source property, but not set Text binding object, will look up Source property of DataContext binding object
Example code:


<StackPanel DataContext="{X:Static SystemFonts.IconFontFamily}"> 
    <TextBox Margin="5" Text="{Binding Path=Source}">
    </TextBox> 
</StackPanel>
<TextBlock Margin="3" Name="lblSampleText" 
FontSize="{Binding ElementName=sliderFontSize,Path=Value Mode="TwoWay"}"
Text="{Binding ElementName=txtContent,Path=Text}" Foreground="{Binding ElementName=lstColors,Path=SelectedItem.Tag}" ></TextBlock>

You can also use code to create a binding:


Binding binding = new Binding();
 binding.Source = sliderFonSize;  
 binging.path=new PropertPath("Value") 
 binding.Mode=BindignMode.TwoWay;
 txt.SetBinding(TextBlock.FontSize,binding)

2. The enumerated values of BindingMode are:

1) OneWay
(2) TwoWay
OneTime: Set the target attribute value according to the source attribute value, and subsequent changes will be ignored unless the BindingExpression.UpdateTarge method is called
OneWayToSource: similar to OneWay, but in the opposite direction, used for the target attribute is not dependent attribute case
Default: the default value, according to the target property to determine the binding type. Each dependency property is used by one metadata, ES66en.BindsTwoWayByDefault, to identify the oneway binding or twoway binding

3. When the data is updated from the target to the binding source (binding mode is twoway or onewaytosource), the update behavior (when to update) is controlled by the Binding. UpdateSourceTrigger enumeration attribute, and the values of UpdateSourceTrigger are:

PropertyChanged: Updated immediately when the target attribute changes

LostFocus: Update the source when the target attribute changes and the target loses focus

Explicit: It cannot be updated unless the method BindingExpression.UpdateSource () is called

Default: according to the target attribute metadata (ES93en. DefaulUpdateSourceTrigger) to determine the update behavior, the default behavior of most attributes is PropertyChanged

4.MultiBinding: Bind multiple objects to one control, mainly using StringFormat


<ListBox ItemsSource="{StaticResource MyData}"> 
<ListBox.ItemTemplate> 
<DataTemplate> 
<TextBlock>
<TextBlock.Text> 
<MultiBinding StringFormat="{}{0} -- Now only {1:C}!">
<Binding Path="Description"/> <Binding Path="Price"/> </MultiBinding> 
</TextBlock.Text> 
</TextBlock> 
</DataTemplate>
</ListBox.ItemTemplate> 
</ListBox>

5.ObjectDataProvider: Get information from another class, only used for data query,IsAsynchronous=true, can make ObjectDataProvider executed in the background, so that even if an exception occurs, it will not affect the display of the bound control:


<ObjectDataProvider x:Key="productsProvider" ObjectType="{x:Type local:StoreDB}"
MethodName="GetProducts"></ObjectDataProvider>

6. WPF derived from ItemsControl class can display list, to be able to support the collection of data binding elements including ListBox, ComboBox, ListView and DataGrid Menu, Treeview, ItemsControl has three important attributes:

ItemsSource: To point to a collection, the combination must support the IEnumerable interface, which contains all the elements to be shown in the list. However, the basic IEnumerable interface only supports read-only bindings, so that changes can be directly reflected on the bound controls need to use the ObservablCollection class
DisplayMemberPath: Determine the properties of the object to be displayed. If not set, the value returned by the object's ToString() method will be displayed
ItemTemplates: Accept 1 data template to create visual appearance for each item

7. The types inherited from IEnumerable interface support binding to list-like elements. Most collection classes do not inherit from INotifyCollectionChanged interface, and WPF provides a collection using INotifyCollectionChanged interface, ObservableCollction class

Bind Grid to the SelectItem property of the lstProducts object


<Grid DataContext="{Binding ElementName=lstProducts,Path=SelectedItem}">....</Grid>

9. When binding, the bound data object may not already exist (you can see whether the object has been defined in xaml when binding the control object). In this case, you can still bind the object class property (Binding Path) in Xaml, and then bind to the control after generating the data object in the code

10. The WPF list control provides UI virtualization (UI Virtualization) functionality to improve the performance of large lists. UI virtualization is a technique for creating container objects for lists only for the currently displayed items

11. Data validation: Used to capture illegal data

ExceptionValidationRule verification: When validation fails, WPF sets Validation.HasError to True on the binding element,WPF automatically switches the template used by the control to the template defined by ES168en.ErrorTemplate, creates an ValidationError object containing the error details, and adds it to the Validation.Errors collection. If the Binding.NotifyOnValidationError attribute is set to True,WPF raises an ES177en.Error event on the control

IDataErrorInfo class: Raises an error in the data object and sets the DataErrorValidationRule validation rule in binding. When an attribute is modified, the string indexer in IDataErrorInfo validates the value with the attribute name Key. You can customize validation classes and respond to validation errors

12. Binding:Binding source itself is data and does not need to be specified by Path. The following binding means binding Text to string type mystring,mystring itself is data.


<TextBlock Text="{Binding source={StaticResource ResourceKye=mystring},Path=.}">

It is believed that what is described in this paper has a certain reference value for you to learn C# programming.


Related articles: