Setting a custom property within a WPF/Silverlight page

后端 未结 10 1234
萌比男神i
萌比男神i 2020-12-14 15:10

This sounds like it should be simple. I have a Page declared in XAML in the normal way (i.e. with "Add new item...") and it has a custom property. I\'

10条回答
  •  长情又很酷
    2020-12-14 15:25

    My suggestion would be a DependencyProperty with a default:

        public int MyProperty
        {
            get { return (int)GetValue(MyPropertyProperty); }
            set { SetValue(MyPropertyProperty, value); }
        }
    
        public static readonly DependencyProperty MyPropertyProperty =
            DependencyProperty.Register("MyProperty", typeof(int), typeof(MyClass), 
                   new PropertyMetadata(1337)); //<-- Default goes here
    

    See the properties of controls as something you expose to the outside world to use.

    If you wish to use your own property, you can use either ElementName or RelativeSource Bindings.

    About the overkill thing, DependencyProperties go hand in hand with DependencyObjects ;)

    No further XAML needed, the default in the PropertyMetadata will do the rest.

    If you really wish to put it in the XAML, go for the base class solution, or gods forbid, introduce an attachable property, which can be used on any other control as well.

提交回复
热议问题