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?
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
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); }
}
© 2022 - 2024 — McMap. All rights reserved.