WPF getting started tutorial series 11-dependency attributes (1), wpf getting started tutorial

Source: Internet
Author: User

WPF getting started tutorial series 11-dependency attributes (1), wpf getting started tutorial

1. Basic Introduction to dependency attributes

This article describes dependency attributes of another important part of WPF.

As we all know, WPF has brought about many new features. One of them is to introduce a new property mechanism-dependency attribute. The purpose of dependency properties is to implement style, automatic binding, animation, and other features in WPF. The emergence of dependency properties is derived from the special Rendering Principle of WPF, and. NET Common properties are different. The value of dependency properties is determined by multiple providers, and it has the ability to transmit change notifications built in.

Dependency properties are basically applied to all elements of WPF that need to set properties. The dependency attribute determines its value based on multiple provided objects (such as animations, parent elements, bindings, styles, and templates), and the value can also respond to changes in a timely manner.

The dependency attribute is an attribute that can have no value and get a value (dependent on others) from the data source through Binding. Objects with dependency attributes are called "dependent objects ". The dependency attribute focuses on the word "dependency". Since it is dependent, that is, the change process of the value of the dependency attribute must be related to other pairs, if A is not dependent on B, B depends on A or is dependent on each other.

 

To put it bluntly, the so-called dependency mainly applies in the following places:

1. Bidirectional binding. With this, the dependency item attribute does not need to write code or implement any interfaces. It also supports bidirectional binding. For example, I bound the employee object name to the shake text box. Once bound, the employee name will change as long as the value in the text box changes, and vice versa;

2. Trigger. This item is very important in WPF. For example, if the background of a button is red, I want it to move the mouse over it and the background turns green. Once the mouse is removed, the button returns red.

In traditional Windows programming, you will find a way to handle some events, or delegate them, and write a bunch of code. It tells you that with the dependency attribute, you do not need to write a line of code, and all the processing is automatically processed by the WPF property system. The trigger only temporarily changes the attribute value. When the trigger is complete, the attribute value is automatically restored ".

3. Additional attributes. The additional property is also A dependency property. It can postpone some attributes of type A to the runtime and set them according to the specific circumstances of type B, in addition, the same attribute value can be maintained by multiple types of objects at the same time, but the attribute values of each instance are independent.

4. When the attribute is changed, the values of other attributes are also changed. For example, when the TogleButton is pressed, A drop-down box is displayed.

 

Compared with traditional CLR attributes and object-oriented attributes, dependency attributes have many novelty, including:

1. Introduction of new functions: added attributes change notifications, restrictions, verification, and other functions. This allows us to conveniently implement our applications and greatly reduce the amount of code, many previously impossible functions can be easily implemented.
2. Memory saving: During WinForm and other project development, you will find that the attributes of the UI control are usually the initial values assigned. storing a field for each attribute is a huge waste of memory. The WPF dependency attribute allows an object to be created without the space used to store data (that is, the space occupied by the field) and retain the default value only when data is needed. The ability to borrow data from other objects or allocate space in real time-this type of object is called a dependent object, and its ability to acquire data in real time depends on the dependency attribute. In WPF development, the dependency object must be used as the host of the dependency attribute to combine the two to form a complete Binding target driven by data ..
3. Multiple objects are supported: You can set the value of the dependency attribute in multiple ways. At the same time, it can store multiple values internally. In combination with Expression, Style, and Animation, it can bring us a strong development experience.
In. NET, you should be very familiar with attributes. The fields of the encapsulated class indicate the status of the class and are converted to the corresponding get and set methods after compilation. Attributes can be used by classes or structures. A simple attribute is as follows, which is also a common method:

 

public class Student    {        string m_Name;         public string Name        {            get { return m_Name; }            set { m_Name = value; }        }        static Student()        {               }      }

 

The difference between a dependency attribute and a common. NET attribute is that a common. NET attribute definition only needs to define the values and settings of its set and get blocks. How Should dependency attributes be defined? What are the differences and connections between dependency attributes and attributes? In fact, the implementation of dependency properties is also very simple. You can do it by following the steps below:

Step 1:Let your class inherit from the DependencyObject base class. In WPF, almost all UI elements inherit from DependencyObject. This class encapsulates operations such as storage and access to dependency attributes. The use of static types is related to the internal storage mechanism of dependency attributes. WPF does not store property values in a private variable as common. NET properties do. Instead, it uses a dictionary variable to store the value displayed by users.

Step 2:The Dependency Property definition must use public static to declare a DependencyProperty variable and have a Property as the suffix. This variable is the true Dependency Property. For example, the following code defines a dependency attribute NameProperty:

 

 public static readonly DependencyProperty NameProperty;

 

Step 3:Register the dependency property with the Property System in the static constructor and obtain the object reference. The dependency property is called by DependencyProperty. to create a static Register method, you must pass an attribute name. This name is very important. When defining the Style and Template controls, the value entered in the Property attribute of Setter is the name used when registering the Dependency Property. PropertyType indicates the actual type of the Dependency Property. ownerType indicates which class registers the Dependency Property. Finally, typeMetadata stores some dependent metadata, including the default value used by the Dependency Property, there is also a notification function when the property value is changed. For example, the following code registers the dependency attribute.

 

NameProperty = DependencyProperty. Register ("Name", typeof (string), typeof (Student), new PropertyMetadata ("Name", OnValueChanged ));

 

Step 4:In the previous three steps, we completed the registration of a dependency attribute. How can we read and write this dependency attribute? The answer is to provide an instantiated packaging property of the Dependency Property to implement specific read/write operations. Unlike CLR attributes, dependency attributes operate attribute values through the GetValue () and SetValue () methods instead of directly manipulating private variables. Standard attributes can be used.. NET Property definition syntax for encapsulation, so that dependency attributes can be used as standard attributes. The Code is as follows.

  public string Name        {            get { return (string)GetValue(NameProperty); }            set { SetValue(NameProperty, value); }        }

 

 

Based on the previous four steps, we can write the following code:

 

Public class Student: DependencyObject {// declare a static read-only DependencyProperty field public static readonly DependencyProperty NameProperty; static Student () {// register our defined dependency property Name NameProperty = DependencyProperty. register ("Name", typeof (string), typeof (Student), new PropertyMetadata ("Name", OnValueChanged);} private static void OnValueChanged (DependencyObject o, DependencyPropertyChangedEventArgs e) {// when the value changes, we can perform some logic processing here} // attribute wrapper, use it to read and set the newly registered dependency attribute public string Name {get {return (string) GetValue (NameProperty) ;}set {SetValue (NameProperty, value );}}}

 

Summary:We generally. the. NET property directly encapsulates a private attribute of the class. Therefore, the field is directly read when the value is read. The dependency property is the GetValue () inherited from DependencyObject by calling () it is actually stored in an IDictionary Key-Value Pair Dictionary of DependencyProperty. Therefore, the Key in a record is the HashCode value of this property, value is the registered DependencyProperty.

Related Article

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.