开发者

How to set default value of DependencyProperty of a type derived from DependencyObject

开发者 https://www.devze.com 2023-03-01 17:44 出处:网络
I\'m creating a custom WPF control that\'s NOT a UserControl.This custom control has two properties (UnselectedAppearance and SelectedAppearance).Both of those properties are of the same type (Appeara

I'm creating a custom WPF control that's NOT a UserControl. This custom control has two properties (UnselectedAppearance and SelectedAppearance). Both of those properties are of the same type (Appearance) which derives from DependencyObject. The Appearance class has several DependencyProperties itself. I'd like to know the proper way to set a default value for each of the Appearance properties. I've tried code like the following, but an exception gets thrown 开发者_运维技巧when I try to use my custom control in the designer.

public static readonly DependencyProperty UnselectedAppearanceProperty = DependencyProperty.Register("UnselectedAppearance", typeof(Appearance), typeof(FNDie), new PropertyMetadata(new Appearance()));

Is there some way I can do this?


The default value for a dependency property is shared between all instances of that dependency object so a value other than null usually only makes sense for value types or immutable classes. In other words, you may learn the hard way, that null is probably your best option.

If you desperately need to set a mutable reference value for a dependency property, you can leave the default as null and set it in the constructor. However, you should be aware that doing so will make that property unavailable for being set using a style, which can be a crippling limitation, depending on your needs.


You should initialize all the non-dependency properties in the constructor that you are calling (here the default parameterless one). Dependency properties can be given a default value like you are doing with new PropertyMetadata(new Appearance());


you need to Using Property MetaData like this

class MyValidation
{ 

    public bool status
        {
            get { return (bool)GetValue(statusProperty); }
            set { SetValue(statusProperty, value); }
        }

        public static readonly DependencyProperty statusProperty =
            DependencyProperty.Register("status", typeof(bool), typeof(MyValidation),new PropertyMetadata(false) );

}
0

精彩评论

暂无评论...
验证码 换一张
取 消