How to create a Dependency property on an existing control?

前端 未结 3 1750
清歌不尽
清歌不尽 2021-01-12 05:20

I have been reading on Dependency properties for a few days and understand how they retrieve the value rather than to set/get them as in CLR properties. Feel free to correct

3条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-12 05:52

    You can use attached properties for it.

    Define your property MyInt:

    
    namespace WpfApplication5
    {
        public class MyProperties
        {
            public static readonly System.Windows.DependencyProperty MyIntProperty;
    
            static MyProperties()
            {
                MyIntProperty = System.Windows.DependencyProperty.RegisterAttached(
                    "MyInt", typeof(int), typeof(MyProperties));
            }
    
            public static void SetMyInt(System.Windows.UIElement element, int value)
            {
                element.SetValue(MyIntProperty, value);
            }
    
            public static int GetMyInt(System.Windows.UIElement element)
            {
                return (int)element.GetValue(MyIntProperty);
            }
        }
    }
    
    

    Bind label content:

    
    
        
            
    
    

提交回复
热议问题