Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF Dependency Property as Enum Collection

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?

like image 401
Evil Str Avatar asked Nov 09 '22 11:11

Evil Str


1 Answers

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))
like image 199
almulo Avatar answered Nov 14 '22 21:11

almulo