In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Editor to share with you how to bind Binding in WPF, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
Introduction to Binding elements
First of all, steal a picture. This picture vividly illustrates the mechanism of Binding.
The main binding class introduced here is System.Windows.Data.Binding. If anything else is involved, it will be briefly described and will not be explained too much.
The following is a brief introduction to the three most basic (most commonly used) attributes:
1. Path-- path, which is used to index to specific attributes, and writing is often omitted. Examples are as follows:
Where Path= can be omitted because the Binding element contains a constructor with parameters whose argument is path. In addition, in the example, A.B needs to be specific to the attribute, and if An is already a specific property that needs to be bound, you can replace A.B with A. That is, the simplest format is:
2. Mode-- mode, which is used to specify the update direction of the data. It is an enumerated type, and there are four ways:
OneTime-one-time update (only once), from the data source to the currently used binding property.
OneWay-one-way update, from the data source to the currently used attribute.
OneWayToSource-An one-way update from the currently used property to the data source.
TwoWay-two-way update with the current properties synchronized with the data source.
Note: if not specified, the default mode is used, which is different on different dependency attributes. When using it, you can specify it manually if you are not sure whether its default mode is the one you need.
3. UpdateSourceTrigger-- data source update trigger, which is used to specify when the property value on the control is updated to the data source. It is also an enumeration type. There are three ways:
Explicit-displays updates that cannot be updated until the UpdateSource method is called.
LostFocus-out of focus update
PropertyChanged-this method is used in most cases when the attribute value is changed, but sometimes updating the data source frequently reduces efficiency. For example, in TextBox, if the data source has more data validation, the interface stutters may occur when entering Text.
Note: of course, there are default settings here, but the default values are different for different control properties, but in most cases the default value is PropertyChanged, and the more special one is the Text property of TextBox, whose default value is LostFocus.
Here is one of the most commonly used binding writing methods:
Control binding
Control binding, that is, data synchronization between different controls in the same interface, the most common is the binding between the slider and a text box. In control binding, you need to specify the ElementName property value of the bound class, that is, the property of the control to which the current property is bound. Examples are as follows:
Note: in WPF development, we often do not set the name value for the control, but in the control binding, we must add the value of the Name property to the source control; while some controls may not contain the Name property, we use x:Name to specify the name.
There is a special existence in control binding-template binding-TemplateBinding, which is not on the same inheritance structure as Binding. TemplateBinding is used in the template definition of the control to bind properties in the corresponding control of the template. Examples are as follows:
TemplateBinding can simply be understood as setting ElementName as its parent control in Binding-this is not the case, but only as an auxiliary understanding. TemplateBinding has a lot less attribute content than Binding.
Data binding
Here data binding represents object binding in WPF, that is, a common scenario is to display database data on the interface. In real project development, the MVVM pattern is often used, and data binding will be reflected there, but MVVM pattern development is not described in this section.
Here is the simplest example to explain data binding:
Background class-data source structure:
Class ForDataBinding {public int Count {get; set;}}
Data source initialization-create data and bind it to the interface:
ForDataBinding data = new ForDataBinding (); data.Count = 10 th is. Fordatabase. DataContext = data
Interface control settings-specify which property of the source data the control is bound to:
The DataContext of Grid is set, which means that the internal data context of Grid is based on the set data source. In this example, the Count bound by the Text property looks up the property based on the ForDataBinding class object. That is, the binding path looks down the corresponding attribute in a tree structure based on the current location.
Other elements
Binding in addition to the above, there are other property settings, this section will briefly introduce a few of the more commonly used content.
Data format conversion
In data binding, sometimes we need to display data that is different from the source data, such as time format, floating-point format, or more complex, we want multiple attribute combinations in a class object to be displayed together.
Simple data formatting can be handled by StringFormat, such as time formatting as yyyy-MM-dd, floating-point numbers keeping two decimal places, and so on. The code example is as follows:
Background class:
Class SimpleDataConvert {public DateTime Date {get; set;} = DateTime.Now; public float Price {get; set;} = 100.123456f;}
Use:
This.simpleconvert.DataContext = new SimpleDataConvert ()
Interface processing:
The result of the above example is that the Date date is formatted as yyyy-MM/dd; and the Price is displayed with two decimal places.
However, some data display requirements cannot be processed by StringFormat, so you need to use the property Converter of Binding to handle it-- that is, through a value converter. Let's take the time conversion used above as an example. If we want to display the date in yyyyMMdd format in the foreground, the display from the data source to the interface can be handled correctly, but in the interface input, it cannot be correctly converted to source data, that is, the built-in Converter does not support it. In this case, we need to implement the value conversion by ourselves, as shown below:
First, define DateConverter and implement the interface IValueConverter. The code is as follows:
Class DateConverter: IValueConverter {/ public object Convert (object value, Type targetType, object parameter, CultureInfo culture) {if (value.GetType () = = typeof (System.DateTime)) {return ((System.DateTime) value) .ToString ("yyyyMMdd");} else {return value } / public object ConvertBack (object value, Type targetType, object parameter, CultureInfo culture) {if (targetType = = typeof (System.DateTime) & & value! = null) {DateTime dt = DateTime.Now; string valuestr = value.ToString (); if (DateTime.TryParse (valuestr, out dt)) {return dt } else if (valuestr.Length = = 8) {string yearstr = valuestr.Substring (0,4); string monthstr = valuestr.Substring (4,2); string daystr = valuestr.Substring (6,2); if (DateTime.TryParse (string.Format ("{0}-{1}-{2}", yearstr, monthstr, daystr, out dt)) {return dt;}} return value;}}
Then add a reference to the Xaml file:
Because the DateConvert is defined directly under the current form class namespace, it has added the following space by default, and if it is defined in another location, you need to add the space reference manually.
Xmlns:local= "clr-namespace:Binding_Demo"
Resource definition to facilitate reference in the control
Finally, the value converter is applied to the control, as follows:
At this point, a simple value converter is complete.
Data verification
The validation in the binding mainly designs four properties:
ValidatesOnDataErrors or ValidatesOnNotifyDataErrors (available after WPF 4.5)-used in combination with DataErrorValidationRule or NotifyDataErrorValidationRule
ValidatesOnExceptions-used in combination with ExceptionValidationRule
NotifyOnValidationError-controls whether Validation.Error events are triggered for additional content processing
ValidationRules-validation rules, used to define a set of validation rules
Let's briefly introduce the use of validation rules with exception validation rules-there are many things involved in validation processing, and this section alone cannot be described completely, so we only list the simplest ways to use them:
The first is the definition of the background class:
Class ForExceptionValidate {private int max; public int Max {get {return max;} set {if (value > 100) {throw new Exception ("Max cannot exceed 100");} max = value;}} this.forvalidate.DataContext = new ForExceptionValidate ()
Then the interface uses:
In this example, the exception thrown in the background class is handled as the result of validation of the interface-- so although exception trapping is not explicitly used here, the program does not crash.
Dependency attribute
Finally, let's briefly talk about dependent attributes, all of the above binding bases need to rely on dependent attributes. All properties that require binding functionality are defined by the corresponding dependency attribute (System.Windows.DependencyProperty). In WPF, we spend most of our time using dependency attributes-various bindings, while our own definitions rely on attributes relatively rarely, so we won't talk about how to define dependency attributes here.
These are all the contents of the article "how to bind Binding in WPF". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.