WPF Enum Flags Dependency property in XAML property editor

503 views Asked by At

I am developing custom WPF UserControl which has few Dependency Properties. One of the properties is enum flags. I am trying to check if it is possible to set this property from Designer in property grid.

Here is the property

    public Letters Letter
    {
        get
        {
            return ((Letters)GetValue(LetterProperty));
        }
        set
        {
            SetValue(LetterProperty, value);
        }
    }

    private static readonly DependencyProperty LetterProperty =
        DependencyProperty.Register("LetterProperty", typeof(Letters), typeof(TestUserControl), new PropertyMetadata(new PropertyChangedCallback(OnLetterChanged)));



    private static void OnLetterChanged(DependencyObject sender, DependencyPropertyChangedEventArgs args)
    {
        return;
    }

    [Flags]
    public enum Letters
    {
        A = 1,
        B = 2,
        C = 4,
        D = 8
    }

    private void TxtBlock_Loaded(object sender, RoutedEventArgs e)
    {
        OutputText = "";

        foreach (Letters letter in Enum.GetValues(typeof(Letters)))
        {
            if ((letter & Letter) != 0)
            {
                OutputText += letter + Environment.NewLine;
            }
        }
    }

Setting multiple flags from XAML works fine and I am getting proper value set.

<Border BorderThickness="2" BorderBrush="Black">
<local:TestUserControl Letter="A,B,C"/>

Main Window

But I want to be able to set multiple choices via Properties Grid. Currently grid is listing all enum values as a drop down menu.

Properties Grid

There seems to be solutions for Windows Forms by deriving from UITypeEditor. I am looking for ways of implementing this in WPF without using 3rd party libraries and Frameworks (Telerik, XCEED etc.)

Thanks!

1

There are 1 answers

0
juster zhu On

It is not recommended to use enumerations because enumeration is not good for property notifications. Use the int type of attribute to agree to what each number represents.