When should I use FrameworkPropertyMetadata or UIPropertyMetadata over plain PropertyMetadata?
Asked Answered
E

2

91

When looking at sample attached properties and behaviors, I've seen a mishmash of uses of FrameworkPropertyMetadata, UIPropertyMetadata and PropertyMetadata. Since they all form an inheritance hierarchy, how do I choose which one to use?

Erstwhile answered 21/3, 2010 at 12:11 Comment(0)
R
92

These classes are to report some behavior aspects of a dependency property.

Check the different classes for the options they provide.

For example,

if you just want to back a property by dp and provide a default value, use PropertyMetadata,

if you want to specify animation behavior, use UIPropertyMetadata,

but if some property affects wpf framework level stuffs eg element layout, parent layout or databinding, use FrameworkPropertyMetadata.

Details you can check on msdn http://msdn.microsoft.com/en-us/library/ms751554.aspx

Rattlesnake answered 21/3, 2010 at 12:34 Comment(4)
The real question is, why does the propdp snippet use UIPropertyMetadata, especially since there are no PropertyMetadata subclasses in Silverlight? It drives me nuts.Pless
That's because same snippets are shared between WPF and Silverlight. You can try different snippets for silverlight from this link: blog.nerdplusart.com/archives/silverlight-code-snippetsRattlesnake
MSDN says "In general, you should use FrameworkPropertyMetadata, particularly if your property has any interaction with property system and WPF functions such as layout and data binding." - (Specifying Metadata) msdn.microsoft.com/en-us/library/ms751554.aspxConch
What kind of data binding should FrameworkPropertyMetadata be used for? I simply want a property that is bound to IsEnabled of a control.Balfour
S
2

One useful feature of FrameworkPropertyMetadata is that you can define the behaviour BindsTwoWayByDefault. Otherwise the dependency property is OneWay by default.

When you need a two way binding for a dependency property, then normally you always need to define Mode=TwoWay for each binding. If you set this mode as default, you don't need to set it for each binding anymore.

You set the behaviour like this:

new FrameworkPropertyMetadata(_myDefaultValue_, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault)

Complete example:

public static readonly DependencyProperty IsSelectedProperty = DependencyProperty.Register(
    "IsSelected", typeof(bool), typeof(MyClass),
    new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.BindsTwoWayByDefault);

public bool IsSelected
{
    get { return (bool)GetValue(IsSelectedProperty); }
    set { SetValue(IsSelectedProperty, value); }
}
Stolon answered 1/9, 2023 at 6:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.