Enum as a DependencyProperty of a UserControl

BitSmithy 1,751 Reputation points
2021-09-27T15:24:11.943+00:00

Hello,

I want to do a UserControl which has enum dependency property.

Sample of enum

Enum MyEnum
{
A,
B,
C
}

This dependency property should work if I define UserControl in XAML.

<local:MyUserControl x:Name="MUC1" MyEnum="A"></local:MyUserControl>

And should work if I want to define or change the user control in code behind.

MUC1.MyEnum = MyEnum.B;

How to do such enum dependency property

Universal Windows Platform (UWP)
0 comments No comments
{count} votes

Accepted answer
  1. Nico Zhu (Shanghai Wicresoft Co,.Ltd.) 12,851 Reputation points
    2021-09-28T02:21:24.043+00:00

    Hello, Welcome to Micorosoft Q&A,

    How to do such enum dependency property

    You could refer to the following, and make enum first, and then define the DependencyProperty in the usercontrol, set the type as MyEnum, When you update Ownenum property, it will invoke CallBack method, you could do some logic in the callback method. For more please refer to custom dependency document.

    public enum MyEnum  
    {  
        A,  
        B,  
        C  
    }  
    public sealed partial class CustomControl : UserControl  
    {  
        public CustomControl()  
        {  
            this.InitializeComponent();  
        }  
      
        public MyEnum Ownenum  
        {  
            get { return (MyEnum)GetValue(OwnenumProperty); }  
            set { SetValue(OwnenumProperty, value); }  
        }  
      
        // Using a DependencyProperty as the backing store for Ownenum.  This enables animation, styling, binding, etc...  
        public static readonly DependencyProperty OwnenumProperty =  
            DependencyProperty.Register("Ownenum", typeof(MyEnum), typeof(CustomControl), new PropertyMetadata(0, new PropertyChangedCallback(CallBack)));  
      
        private static void CallBack(DependencyObject d, DependencyPropertyChangedEventArgs e)  
        {   // process logic  
            var control = d as CustomControl;  
            switch ((MyEnum)e.NewValue)  
            {  
                case MyEnum.A:  
      
                    break;  
                case MyEnum.B:  
      
                    break;  
                case MyEnum.C:  
      
                    break;  
                default:  
                    break;  
            }  
        }  
    }  
    

    If the response is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments

0 additional answers

Sort by: Most helpful