question

BitSmithy-4663 avatar image
0 Votes"
BitSmithy-4663 asked NicoZhu-MSFT edited

Enum as a DependencyProperty of a UserControl

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

windows-uwp
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

NicoZhu-MSFT avatar image
0 Votes"
NicoZhu-MSFT answered NicoZhu-MSFT edited

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.


5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.