WPF Study Notes-5. dependencyproperty

Source: Internet
Author: User

Dependency Property is not a language-level "attribute", but a "function" provided by WPF ". It encapsulates some internal behaviors on the basis of CLR property, so that declarative XAML has more powerful action control capabilities, obviously, this is much easier and more natural than writing behavior events using program design code.

Features of dependency attributes:

(1) Use an efficient sparse storage system. This means that, without setting local values, all the dependency attributes of the same type of objects will share the default settings, greatly saving the memory overhead.
(2) The dependency property has the ability to change notification. When the attribute value changes, the Association behavior can be triggered through pre-registered metadata information.
(3) The dependency attribute can inherit the attribute value from its parent level in the tree.
(4) The dependency attribute can obtain the final value from multiple providers based on the priority.

1. Dependency attribute implementation

The implementation of dependency properties is simple:

(1) Its Type inherits from dependencyobject, and almost all WPF controls indirectly inherit from this type.
(2) declare a dependencyproperty using public static. This field is the true dependency attribute (field ).
(3) register the metadata of the dependency attribute in the static structure and obtain the object reference.
(4) Provide an instantiated packaging property for dependency properties. Use the dependencyobject method as the reader/accessor.

Public class myclass: dependencyobject
{
Public static readonly dependencyproperty testproperty;

Static myclass ()
{
Testproperty = dependencyproperty. Register ("test", typeof (string), typeof (myclass ),
New propertymetadata ("Hello, world! ", Ontestchanged ));
}

Private Static void ontestchanged (dependencyobject o, dependencypropertychangedeventargs E)
{

}

Public String Test
{
Get {return (string) getvalue (testproperty );}
Set {setvalue (testproperty, value );}
}
}

Tip: You can use "propdp + TAB" in vs2008 to quickly generate dependency attribute code.

2. Change Notification

When the dependent attribute values change, WPF calls some "associated behaviors" through the pre-registered metadata (metadata) information. In this way, we can complete Behavior Control in the XAML declaration, such as starting or stopping an animation.

We tried to bind the custom Dependency Property we created above to the relevant control as the source.

Public partial class window1: Window
{
Myclass O;

Public window1 ()
{
Initializecomponent ();

O = new myclass ();

VaR binding = new binding ("test") {source = O, mode = bindingmode. twoway };
This. textbox1.setbinding (textbox. textproperty, binding );
}

Private void btntest_click (Object sender, routedeventargs E)
{
O. test = datetime. Now. tostring ();
}
}

Window
When the object is initialized, textbox1.text is automatically bound to the default value of myclass. testproperty "Hello, world! "(Refer
Metadata registration code that is statically constructed by myclass ). Textbox1.text
Will be automatically updated synchronously, This is the behavior of the dependency attribute. Of course, we should also provide a fully XAML-based declaration demonstration, instead of the above C # code.

<Window X: class = "learn. WPF. window1"
Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "window1">
<Grid>
<Textbox X: Name = "textbox1"/>
<Label X: Name = "label1" content = "{binding elementname = textbox1, Path = text}"/>
</GRID>
</WINDOW>

Label1.content
Bound to the dependency attribute textbox1.text. Whenever we modify textbox1.text, label1.content
Changes will be made synchronously, so we do not need to write any code for these actions. Obviously, this greatly simplifies the behavior control capability of XAML, especially
Functionality.

WPF provides a mechanism called trigger to work with dependency attributes. We use a simple property trigger to see the effect.

<Window X: class = "learn. WPF. window1"
Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "window1">
<Grid>
<Button X: Name = "btntest">
<Button. Style>
<Style targettype = "{X: type button}">
<Style. triggers>
<Trigger property = "ismouseover" value = "true">
<Setter property = "foreground" value = "red"/>
</Trigger>
</Style. triggers>
</Style>
</Button. Style>
</Button>
</GRID>
</WINDOW>

When
When the dependency attribute button. ismouseover changes (= true), the trigger will be executed and set
Foreground = red. Obviously, this is much easier than processing the mouseenter event. The key is the UI.
Designers can achieve the desired results without writing code. Besides attribute triggers, WPF also provides data triggers and event triggers.

3. Property Value inheritance

This
Inherit non-oop inheritance. It is intended that the settings of the parent element will be automatically passed to the child elements of all layers.
(The element can inherit the value of the dependency attribute from its parent level in the tree ). In fact, it is very simple and familiar. When we modify the font settings of the form parent container control, all levels of child controls will automatically use the font settings
(No custom settings have been made.) I believe you have used it in winform.

<Window X: class = "learn. WPF. window1"
Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "window1" fontsize = "20">
<Grid>
<Textbox X: Name = "textbox1"/>
<Label X: Name = "label1" content = "Hello, world! "/>
<Button X: Name = "btntest" content = "test"/>
</GRID>
</WINDOW>

Window. fontsize affects the font size of all internal elements. This is called property value inheritance. Of course, once the child element provides explicit settings (such as label1.fontsize in the following example), this inheritance will be interrupted.

<Window X: class = "learn. WPF. window1"
Xmlns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"
Xmlns: x = "http://schemas.microsoft.com/winfx/2006/xaml"
Title = "window1" fontsize = "20">
<Grid>
<Textbox X: Name = "textbox1"/>
<Label X: Name = "label1" content = "Hello, world! "Fontsize =" 10 "/>
<Button X: Name = "btntest" content = "test"/>
</GRID>
</WINDOW>

Note that not all dependency attributes inherit the settings of the parent element.

4. Multi-provider priority

WPF allows us to set the value of the dependency attribute in multiple places, which is indeed very convenient, but there are also many problems. For example, in the following example, we set the background color of the button in three places, but which one will work at the end?

<Button X: Name = "button1" background = "red">
<Button. Style>
<Style targettype = "{X: type button}">
<Setter property = "background" value = "green"/>
<Style. triggers>
<Trigger property = "ismouseover" value = "true">
<Setter property = "background" value = "blue"/>
</Trigger>
</Style. triggers>
</Style>
</Button. Style>
Click
</Button>

The exact answer is "<button background = 'red'>". Why? The priority rule in WPF determines that the "local value" has the highest priority.

Local value> style trigger> template trigger> style setting program> topic style trigger> topic style setting program> property value inheritance> Default Value

Such a process is called "basic value judgment ". Specifically, the local value indicates that dependencyobject. setvalue is called directly or indirectly, that is, the value of the dependency attribute is displayed. We can use the following code to clear the local value settings.

This. button1.clearvalue (button. backgroundproperty );

Although we have obtained the basic value, it is not over yet. Next we will see a few more powerful players playing. Their priority level is higher, and the dependency attributes must pass through one by one before being finalized.

Basic value judgment-> Expression calculation-> apply animation-> constraint (coerce)-> verify-> final result

(1) verification refers to the validatevaluecallback delegate method provided by the dependency attribute. It determines whether the attribute value setting is valid;
(2) The restriction is the coercevaluecallback delegate provided during registration. It verifies whether the attribute value is within the permitted range, for example, 100 less than or equal to 9;
(3) An animation is a special behavior that has a higher priority than the basic settings;
(4) If the dependent attribute value is a calculated expression (system. Windows. expression, for example, the binding syntax in the preceding example), WPF will try to calculate the result of the expression.
(5) The basic value is the display settings provided above, and its priority is better determined.

5. Additional attributes

An additional property is a special dependency property that looks odd, especially for those of us who are familiar with object-oriented rules. Let's look at the example below.

<Dockpanel>
<Checkbox dockpanel. Dock = "TOP"> Hello </checkbox>
</Dockpanel>

Dockpanel. Dock is the dependency attribute defined in dockpanel, but it appears on the declaration of sub-elements. It looks strange.

<Stackpanel textelement. fontsize = "30" textelement. fontstyle = "blod">
<Button> help </button>
<Button> OK </button>
</Stackpanel>

Textelement. fontsize, textelement. fontstyle does not belong to stackpanel or button, but can complete the font definition of the element tree.

Appendix
Adding a property is strictly a XAML concept, and the Dependency Property is WPF.
Concept. Additional properties are usually used for layout settings of interface elements. This special extension mechanism allows the parent element to pass some custom settings to all child elements without having to have the same
Dependency attribute. This kind of application method is somewhat extended, and it is really not easy to understand at the first time.

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.