Introduction to WPF (5) WPF dependency attributes and wpf dependency

Source: Internet
Author: User

Introduction to WPF (5) WPF dependency attributes and wpf dependency

In. NET, events also have attributes. in WPF, route events and dependency attributes are added. I recently did not know what the WPF dependency attribute is for when I write a project. I thought it was for use when I used the dependency attribute. NET attributes, but they are not. By reading articles and reading WPF books, you have learned how to use the dependency attributes of WPF, let's take a look at why the dependency attribute is added to WPF today?


1. What are dependency attributes?

Dependency attributes in WPF are different from those in. NET, because several important features in WPF require support for dependency attributes, such as data binding, animation, and style setting. Most of WPF attributes are dependency attributes, but they use common attributes. the NET property process is packaged. Through this packaging, you can use the Dependency Property just like using the property. Later, we will explain how to wrap it in this way. The old technology is used to wrap the design concept of the new technology without interfering with. NET. Dependency attributes in WPF have the following three advantages:

1. Dependency attributes include attributes change notifications, restrictions, verification, and other functions. This makes it easier to implement applications and greatly reduces the amount of code.

2. Memory saving: In WinForm, each UI control attribute is assigned an initial value, so that each same control will save an initial value in the memory. The dependency attribute of WPF solves this problem well. It uses the hash table Storage Mechanism internally to save only one copy of the values of the same attributes of multiple identical controls.

3. Multiple objects are supported: You can set the value of the dependency attribute in multiple ways. You can use expressions, styles, and bindings to set values for dependency attributes.


We have been talking about attributes just now. Let's take a look at what attributes are. First, create a class Person with the name attribute.

Public class Person


Public string name {set; get ;}


The above is the created property. It looks very easy. Attribute creation is so simple that it can be initialized where we want to use this class.

Since most of the properties in WPF are dependency properties, I have read how to create dependency properties.

1. the type of the dependency attribute inherits from the DependencyObject class.

2. Use public static to declare a DependencyProperty variable, which is a true Dependency Property.

3. Type Static constructors use the Register Method to Register the metadata of dependency properties.

4. Provide the packaging attribute of the dependency attribute to perform read/write operations on the dependency attribute.

The creation code is as follows:

// The dependency attribute must be in the DependencyObject

Public class Person: DependencyObject


// CLR property wrapper enables the Dependency Property NameProperty to be used externally as a common property

Public string Name


Get {return (string) GetValue (NameProperty );}

Set {SetValue (NameProperty, value );}



// The dependency attribute must be static readonly.

// DependencyProperty. Register parameter description

// The first parameter is of the string type and is the attribute name.

// The second parameter is the type of the Dependency Property.

// The third parameter is the type of the Dependency Property.

// The fourth parameter is the FramWorkPropertyMetadata object with additional property settings.

Public static readonly DependencyProperty NameProperty =

DependencyProperty. Register ("Name", typeof (string), typeof (Person), new PropertyMetadata ("DefaultName "));



The code above shows that the dependency attribute is read and written by calling the GetValue and SetValue of DependencyObject. It uses a hash table for storage. The corresponding Key is the HashCode Value of the attribute, while the Value is the registered DependencyPropery; the attribute in C # Is the encapsulation of a private field. You can perform operations on this field to read and write the attribute. Attribute is the packaging of fields. In WPF, attributes are used to encapsulate dependency attributes.


Ii. Priority of dependency attributes

The WPF property system provides a powerful method to determine the value of dependency properties by multiple factors, this allows you to implement functions such as real-time property verification, post-binding, and notification of changes to other property values to relevant properties. The exact sequence and logic used to determine the dependency attribute values are quite complex. Understanding this sequence helps avoid unnecessary attribute settings, and may clarify obfuscation, so that you can correctly understand why some attempts to influence or predict dependency attribute values ultimately fail to reach the expected value. The dependency property can be set in multiple locations. The interface code is as follows:


The local property set has the highest priority when set, except for animation values and force. If you set a value locally, you can expect the value to take precedence over any style or control template. In the above example, the Background is set to Red locally. Therefore, even if it is an implicit style, it will apply to all elements of this type in the scope. The style defined in this scope is not given the highest priority to the Background property and its value. If the local value red is deleted from the Button instance, the style gets the priority, and the Button gets the Background value from the style. In this style, the trigger has a priority, so when the mouse is on the button, the button is blue, and in other cases it is green.

The following figure shows the priority list of dependency attributes found on the Internet. You can pay attention to the priority when using attributes later.



Iii. Inheritance of dependency attributes

Inheritance of dependency attributes is a function of the WPF property system. Property Value inheritance allows the child element in the element tree to obtain the value of a specific property from the parent element and inherit the value, just as it is set at any position in the nearest parent element. The parent element may have obtained its value through property value inheritance, so the system may always recursively go to the page root. Property Value inheritance is not a default property system action. Attributes must be created using specific metadata settings to enable property value inheritance for child elements.


You may have discovered the problem when you see the above picture: StatusBar does not explicitly set the FontSize value, but its font size does not inherit the value of Window. FontSize, but retains the default value of the system. This problem occurs because not all elements support property value inheritance, such as StatusBar, Tooptip, and Menu controls. In addition, controls such as StatusBar intercept properties inherited from the parent element, and this property does not affect the child elements of the StatusBar control. For example, if we add a Button in StatusBar. The FontSize attribute of the Button will not be changed, and its value is the default value.

Iv. Custom dependency attributes

If you want to inherit the Dependency Property, you can customize the Dependency Property to inherit the property value.

Steps for customizing attributes:

1. Create a derived class CustomStackPanl


Create a derived class CustomButton


2. Introduce the namespace in the window control

Xmlns: sys = "clr-namespace: System; assembly = mscorlib"

3. Add a Button on the page




V. Dependency Property Verification and forcible Functions

Possible errors will be considered when writing code. When defining attributes, you also need to consider the possibility of setting attributes incorrectly. For traditional. NET attributes, you can verify the attribute values in the property configurator. An exception can be thrown if the value does not meet the conditions. However, this method is not suitable for dependency attributes because the dependency attributes directly set their values through the SetValue method. However, WPF has a replacement method. WPF provides two methods to verify the value of dependency properties.

1. ValidateValueCallback: This callback function can accept or reject new values. This value can be used as a parameter of the DependencyProperty. Register Method.

2. CoerceValueCallback: This callback function can forcibly change the new value to an acceptable value. For example, if the value range of a dependent attribute's working age is 25 to 55, you can force modify the set value in the callback function. for values that do not meet the conditions, force change to a value that meets the conditions. If it is set to a negative value, it can be forcibly changed to 0. The callback function PropertyMetadata constructor parameter is passed.


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: 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.