WPF Dependency Property as Enum Collection

632 views Asked by At

I have a enum like this:

public enum Filter
{
   Filter1,
   Filter2,
   Filter3,
   Filter4
}

And I would like to use like this:

<local:myComponent FilterList={Filter.Filter1, Filter.Filter2} />

I was trying to use this: wpf dependency property enum collection but it didin't work as I expected. I don't want the user to type freely, I want them to use the list of enum.

How should I do that?

2

There are 2 answers

6
almulo On

EDIT: In case your FilterList is a collection... Well, it shouldn't. Or better said, it doesn't have to be a collection and it would just adds complexity to make it one.

Enums can be used as Flags, which means that you can set multiple values to a single Enum property as long as you observe some special considerations.

Check this artcile in the MSDN for more info about Flag Enumerations: https://msdn.microsoft.com/en-us/library/vstudio/ms229062(v=vs.100).aspx

And this for more info: http://www.codeproject.com/Articles/396851/Ending-the-Great-Debate-on-Enum-Flags

But, basically, you should define your enum as follows:

public enum Filter
{
   Filter1 = 1,
   Filter2 = 2,
   Filter3 = 4,
   Filter4 = 8
}

Then define your FilterList property as of type Filter only, not a collection.

public Filter FilterList
{
    get { ... }
    set { ... }
}

Once you've done that, you can set the property from XAML as follows:

<local:myComponent FilterList="Filter1, Filter2" />

Check this article for more info: http://blog.martinhey.de/en/post/2012/06/13/Flagged-enums-and-XAML-syntax.aspx

And you can set it and check it programatically using simple bitwise operations.

Setting:

FilterList = Filter.Filter1 | Filter.Filter2;

Checking:

if ((FilterList & Filter.Filter3) == Filter.Filter3)

...or...

if (FilterList.HasFlag(Filter.Filter3))
0
Rachel On

Assuming FilterList is a collection of Filter enum items, does it work to define them like this in your XAML?

<local:myComponent>
    <FilterList>
        <x:Static local:Filter.Filter1 />
        <x:Static local:Filter.Filter2 />
    </FilterList>
</local:myComponent>

I'm not really sure of a shorter way of writing that except perhaps a Converter to convert a csv string to an enum list.