Dependency Property (1) in WPF)

Source: Internet
Author: User

 

WPFIntroduces a new property --Dependency PropertyThe application of this attribute runs through the wholeWPFTo implementStyle, Binding, animation, etc. It is calledDependency PropertyBecause they depend on some otherPropertyAnd the external influence, at any time is to rely on multipleProgramTo determine its value. These providers can inherit property values from the parent element (do not confuse the inheritance relationship with the class), or a continuously changing animation.

ToFontsizeFor example, in the traditional. NetIn programmingFont SizeWill be stored in this classPrivateFields may be initialized using the following default values:

Private double Fntsize= 11;

ThisPrivateThe member variables shouldPublicOfFontsize PropertyAppears:

Public Double Fontsize

{

Get

{

Return Fntsize;

}

Set

{

Fntsize=Value;

...

}

}

in set " ... "indicates that more Code is required. Maybe the widget needs to be changed or at least re-painted. Maybe the fontsizechanged event will happen, for the inheritance of fontsize , you may need to enumerate the elements one by one tree .

All of this, inWPFOfDependency PropertyIs not so troublesome. Everything is "automatic" and no additional code needs to be written. Therefore,Dependency PropertyThe biggest feature is its built-in change notification capability. The power of providing such capabilities to attributes is the ability to directly enable the rich feature in the Declaration tag.WPFThe key to the friendly declaration design is that it uses many attributes. For example,ButtonControls have96Public attributes. attributes can be conveniently stored inXAMLYou do not need to write background code. However, ifDependency PropertyThere is no additional vertical transfer. It is difficult to get the desired results in simple actions such as setting properties without writing additional code.

In this article, we will take a simple look.Dependency PropertyTo make the discussion more specific. Then we will analyze the following three aspects:

1)Change Notification capability

2)Property Value inheritance

3)Supports multiple providers

 

A standard dependency attribute implementation (the following code may be closeFontsizepropertyHowControlClass ):

Public Class Control:Frameworkelement

{

Public Static Readonly Dependencyproperty Fontsizeproperty;

Static Control()

{

Frameworkpropertymetadata Metadata=New Frameworkpropertymetadata();

Metadata.Defaultvalue= 11;

Metadata.Affectsmeasure=True;

Metadata.Inherits=True;

Metadata.Isnotdatabindable=False;

Metadata.Defaultupdatesourcetrigger=Updatesourcetrigger.Propertychanged;

Metadata.Propertychangedcallback=New Propertychangedcallback(Onfontsizechanged);

Fontsizeproperty=Dependencyproperty.Register("Fontsize",Typeof(Double),Typeof(Control),

Metadata,New Validatevaluecallback(Validatefontsize));

}

 

//. NetProperty wrapper (optional)

Public Double Fontsize

{

Get

{

Return(Double)Getvalue(Fontsizeproperty);

}

Set

{

Setvalue(Fontsizeproperty,Value);

}

}

 

//Callback for attribute change (optional)

Static Void Onfontsizechanged(Dependencyobject OBJ,Dependencypropertychangedeventargs E)

{

...

}

 

//Callback for property value verification (optional)

Static Bool Validatefontsize(Object OBJ)

{

Double Dfontsize= (Double)OBJ;

Return Dfontsize> 0 &&Dfontsize<= 35791;

}

}

Fontsizeproperty Called Dependency Property , It is Public And Static This means that this member variable is associated with the class, not the object. Static read-only members can only be set in "class member variable definition" or "static constructor. Generally, classes are called by calling static Dependency. Register Method. This method requires a name ( Fontsize ), An attribute type ( Double ) And the class that owns this property ( Control ). Different Register Method overload, You can input Metadata (Metadata) to tell WPF The default value of the property, how to handle the property, how to handle the callback of the property value change, how to handle the forced value conversion, and how to verify the value.

Finally, it is called Fontsize Will call the property inherited from System. Windows. dependencyobject Of Getvalue And Setvalue Method to implement your own accessors. System. Windows. dependencyobject Is the underlying base class, which has Dependency Property Must be inherited. Getvalue Returns the last SetvalueValue. If Setvalue It is the default value when this property is registered. Fontsize Property wrappers are not required, Control Users may directly call Getvalue And Setvalue Methods, because they are public. To . Net The implementation of the Property package will make the read/write attributes look natural and allow XAML Set Properties.

Note: When running, XAML bypassed . net property wrapper directly sets dependency properties

although XAML the compiler depends on this property package during compilation, but WPF direct call getval UE and setvalue ! Therefore, to enable XAML the setting property is consistent with the setting property using procedural code. In the property wrapper, except getvalue and setvalue the call should not contain any other logic, this is crucial. To add custom logic, add it to the registered callback function.

Even if it is passedGetvalueAndSetvalueWhen the ParameterDependency PropertyThe object is static,GetvalueAndSetvalueBut it is an instance method. The setting and obtaining of their values are related to specific instances. And,GetvalueAndSetvalueAn efficient sparse storage system is used internally.. NetProperty,Dependency PropertyThe implementation saves the memory required to save each instance.

Dependency PropertyThe benefit is far more than memory usage. It collects code that is used to check thread access, request the re-Presentation of container elements, and change notifications, and performs standardized processing, this part of the code was originally written by the property implementer.

For more information, seePost.

 

A za a za fighting!

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.