{"id":1434,"date":"2012-10-29T00:00:00","date_gmt":"2012-10-29T00:00:00","guid":{"rendered":"https:\/\/test.simple-talk.com\/uncategorized\/view-models-with-flags-in-wpf\/"},"modified":"2021-05-17T18:36:11","modified_gmt":"2021-05-17T18:36:11","slug":"view-models-with-flags-in-wpf","status":"publish","type":"post","link":"https:\/\/www.red-gate.com\/simple-talk\/development\/dotnet-development\/view-models-with-flags-in-wpf\/","title":{"rendered":"View-Models with Flags in WPF"},"content":{"rendered":"<div id=\"pretty\">\n<p class=\"start\">The power of XAML databinding is continually nudging me to rethink how I design view-model classes. The latest nudge came when I was working with Windows Presentation Foundation (WPF) and a domain object that contained several related Boolean attributes. At first, I&#8217;d thought of creating a view-model class with a property for each attribute; but previous experience with such a view-model had convinced me that such designs were cumbersome. That&#8217;s when it occurred to me to use .NET&#8217;s flag enumerations. This article discusses such an implementation, as well as some technical lessons that I learned in the process. <\/p>\n<p>The sample code for this article manages a few dog properties as shown in the below form. <\/p>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1591-Sample%20UI-ea5d9cd0-fd4e-4384-86bc-84139cfb4220.PNG\" alt=\"1591-Sample%20UI-ea5d9cd0-fd4e-4384-86bc\" \/><\/p>\n<p>Before we begin though, allow me a warning to both dog lover and software architect. My aptly named &#8220;Demonstration&#8221; solution may fall short in a few areas of personal and professional preference, but no dogs were harmed in the process. <\/p>\n<h2>Enumerated <strong>FLAG<\/strong>S 101<\/h2>\n<p>To work with flag enum classes, you need to understand what makes them different from their more prevalent, non-flag brethren. By doing so, you&#8217;ll not only augment your coding toolbox, but possibly also improve your view, and view-model, designs. <\/p>\n<h3>Definition<\/h3>\n<p>Plain old enums (POE?), to quote MSDN, are &#8220;a distinct type consisting of a set of named constants called the enumerator list&#8221;. You can use any integral type except a <strong>char<\/strong> as values for a POE. The CLR&#8217;s System-defined <strong>[FLAGS]<\/strong> class attribute adds a powerful twist to an enum class. It informs the runtime that the underlying value types now support bitwise operations. <\/p>\n<div class=\"note\">\n<p class=\"note\"><strong>Why Enums?<\/strong> <\/p>\n<p>Truth be told, enums could qualify as syntax sugar as indicated by their omission from the earlier versions of C. Even so, they now exist in most modern programming languages because they allow you to share a multi-valued property across applications. <\/p>\n<p>Imagine if .NET did not support enumerations. Consider the System.IO&#8217;s <strong>FileOpen<\/strong> method which includes two <strong>FileMode<\/strong> and <strong>FileAccess<\/strong> enumerations. How would you rewrite <strong>FileOpen<\/strong> without them? Create several new methods, such as, <strong>FileOpenCreateNewReadWrite<\/strong> or <strong>FileOpenRead<\/strong>? Our new API begins to look unwieldy and maybe a little ugly. <\/p>\n<\/div>\n<p>The below side-by-side comparison from the Demonstration solution highlights our two different enumerations. <\/p>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1591-Enum%20Compare-7548e8f9-562a-43dc-9cf8-b90c9289b1b9.PNG\" alt=\"1591-Enum%20Compare-7548e8f9-562a-43dc-9\" \/><\/p>\n<p>At first blush they look similar except for the <strong>[FLAGS]<\/strong> attribute, which requires the System namespace declaration. Closer examination reveals that the <strong>DogProperties<\/strong>&#8216; values grow as powers of 2. This is not accidental. The pattern allows for binary calculations, as explained shortly, which enables treating an enumerated property as collection of values as shown in the below code snippet. <\/p>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1591-Flag%20Enum%20Sample%20Usuage-48b8ca18-56e2-4da8-90a6-925f9409e0c1.PNG\" alt=\"1591-Flag%20Enum%20Sample%20Usuage-48b8c\" \/><\/p>\n<h3>A Bit of Math<\/h3>\n<p>Underneath the covers .NET knows two things about flag enumerations. First, individual enumerated values equal a binary digit, 0 or 1. Second, each individual enumerated value resides in one and only position in a binary number. The following expressions of a <strong>DogProperties<\/strong> that includes both Big and Loud values illustrates these two facts at work. <\/p>\n<p> Expressed as an Enum<br \/><strong>DogProperties.Big | DogProperties.Loud<\/strong> <\/p>\n<p> Expressed as a sum of 2x<br \/>0 * 25 + 0 * 24 + 1 * 23 + 0 * 22 + 1 * 21 + 0 * 20 + 0 <\/p>\n<p> Expressed as a sum of binary digits<br \/>00000 + 00000 + 00100 + 00000 + 00010 + 00000 + 0 <\/p>\n<p> Expressed as a binary digit<br \/>001010 <\/p>\n<p>Once you appreciate this bit mapping, then you&#8217;ll quickly see that it only requiresa line of codeto determine whether or not our Dog is loud.<\/p>\n<p> Checking FLAG Enum Property in C#<br \/><strong>(Dogproperties &amp; DogProperties.Loud) == Dogproperties.Loud <\/strong> <\/p>\n<p> Checking Property in Binary<br \/>&#160;&#160;&#160;001010<br \/> &amp;&#160;<u>001000<\/u><br \/> &#160;&#160;&#160;001000 == 001000 <\/p>\n<h3>Caveats<\/h3>\n<p>The <strong>FLAG<\/strong> enums have gained a reputation for being difficult. Why? While binary calculations are not inherently tricky, they may trip developers up when they try to combine them, or to perform logical comparisons. For example, do I use an ampersand or pipe character when adding a new value? Which one do I use for checking a logical equality? Recent enhancements in .NET&#8217;s languages can minimize these frustrations, as we will see shortly. <\/p>\n<p>The second hazard is not so easily waved away with magic. The maximum number of Boolean values that are available to a flag enumeration is small. Typically .NET enumerations ride upon 32-bit integers and the <strong>FLAG<\/strong> restriction limits those values to sets supporting binary operations. These two constraints conspire together to limit the maximum uncombined properties in a flag enumeration to thirty. <\/p>\n<div class=\"note\">\n<p class=\"note\"><strong>Why only 30 <strong>FLAG<\/strong>s?<\/strong><\/p>\n<p>The math behind the <strong>FLAGS<\/strong> enum type&#8217;s 30 value limitation is exponential. Calculate the base 2 log of the enumerated value type&#8217;s maximum. Applying this formula to a default .NET enum type equates to log2 (2,147,483,647) or an integer less than 30.999999999328196. <\/p>\n<p>This limitation jives with our newfound understanding that 31 values for a <strong>FLAG<\/strong> enum type demands the largest value equal 231 or 2,147,483,648 which exceeds .NET&#8217;s int.MaxValue. <\/p>\n<\/div>\n<h2>The Demonstration Solution<\/h2>\n<p>It is easy to introduce flag <strong>enums<\/strong> into our solution &#8211; you just add the <strong>DogProperties<\/strong> enum type and add a few values. The real challenge comes in making them easy to code in a XAML world. For our situation, two supporting classes seem to do just that. The first uses .NET extensions to simplify the task of manipulating <strong>DogProperties<\/strong>. The other facilitates communications between XAML and the view-model&#8217;s <strong>DogProperties<\/strong> property. <\/p>\n<h3>Extensions<\/h3>\n<p>While coding a .NET extension method may not be intuitive at first, it is at least formulaic. Create a static class; add a static method; append &#8220;this&#8221; to the first parameter which is same type as target; and code the body. The below snippet is an example of a basic extension method. <\/p>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1591-RemoveValue%20Snippet-37a62682-18b1-4809-92df-5740595a2653.PNG\" alt=\"1591-RemoveValue%20Snippet-37a62682-18b1\" \/><\/p>\n<p>I suspect that few developers find anything complex within this method&#8217;s body. It just executes a binary operation that removes a <strong>dogProperty<\/strong> from <strong>dogProperties<\/strong>. The more germane question is this: &#8216;which of the following lines of code would you prefer writing when in a rush?&#8217; <\/p>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1591-Hard%20or%20Easy%20Flag%20Code-81c6fbed-2056-438f-be83-64d349f4ccfd.PNG\" alt=\"1591-Hard%20or%20Easy%20Flag%20Code-81c6\" \/><\/p>\n<p>There is a great advantage in using extensions to place domain-specific business rules in one spot when you are working with <strong>FLAG<\/strong> enums. Look at the below <strong>AddValue<\/strong> method. It applies a few domain rules that could be easily overlooked by developers working directly with <strong>Dog<\/strong>Properti<strong>es<\/strong>. <\/p>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1591-AddValue-fc5e643e-fef1-41ef-92a3-2a4858cda171.PNG\" alt=\"1591-AddValue-fc5e643e-fef1-41ef-92a3-2a\" \/><\/p>\n<h3>IValueConverter<\/h3>\n<p>WPF developers quickly encounter another one of those little XAML annoyances when binding view-models&#8217; to an enum-based property. It doesn&#8217;t work. XAML&#8217;s designers fortunately predicted problems like this and so they created <em><strong>IValueConverter<\/strong><\/em>. Our demonstration solution implements this interface with a slight twist as show below. <\/p>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1591-Converter-27b5d8bc-6639-4501-bb5e-c8f094069815.PNG\" alt=\"1591-Converter-27b5d8bc-6639-4501-bb5e-c\" \/><\/p>\n<p>DogPropertiesConverter relies heavily on the parameter parameter (that&#8217;s not a typo). Most converters ignore parameter and work with value. Parameter equates to ConverterParameter property value of the converter&#8217;s binding markup. In our case it helps differentiate several XAML controls bound to our view-model&#8217;s <strong>DogProperties<\/strong> property. <\/p>\n<p>Another interesting aspect of the converter code is the inclusion of <strong>Enum.TryParse<\/strong>. While such checks are not mandatory they can prove helpful when debugging. For example, the <strong>TryParse<\/strong> within the <strong>ConvertBack<\/strong> method quickly notifies a developer if they mistyped a markup&#8217;s <strong>ConverterParameter<\/strong> enumerated <strong>DogProperties<\/strong> string value. Would you readily spot the error below? <\/p>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1591-Bad%20Converter%20Value-539db356-373f-4f00-8c76-8466921d5ef3.PNG\" alt=\"1591-Bad%20Converter%20Value-539db356-37\" \/><\/p>\n<p><em>Error Hint: <\/em><em>Look at the <\/em><strong>ConverterParameter<\/strong><em>s<\/em><em>&#8216; values. <\/em><em>Dogs are either &#8216;Big&#8217; or &#8216;Small&#8217;. <\/em><\/p>\n<div class=\"note\">\n<p class=\"note\"><strong>IConverterValue Mechanics<\/strong><\/p>\n<p>Our discussion glosses over <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.windows.data.ivalueconverter.aspx\">IValueConverter implementation<\/a> details. Read MSDN&#8217;s IValueConverter Interface page for the specifics of rolling your own. <\/p>\n<\/div>\n<h3>All Together<\/h3>\n<p>Our handiwork finally comes together starting with the Dog view-model and wraps up with the <strong>MainWindow<\/strong> view. <\/p>\n<p>To implement the <strong>DogProperties<\/strong> property, you just need to add it to the <strong>Dog<\/strong> class as shown in the following snippet. Remembering that view-model classes exist to ease the interaction between the user interface and its models guides our property set&#8217;s body. It implements two desired behaviors as shown in the following snippet. <\/p>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1591-Dog.DogProperties-d49056c5-447e-46be-b6db-b8e3498d6c6f.PNG\" alt=\"1591-Dog.DogProperties-d49056c5-447e-46b\" \/><\/p>\n<p>The first behavior that the setter tackles is the one that enables developers to initialize <strong>DogProperties<\/strong> by passing the <strong>Undefined<\/strong> enumerated value. This skips the binary calculations hidden within the extension methods that do not understand the idea of allowing one value to wipe away all others. (Didn&#8217;t we mention <strong><strong>FLAG<\/strong><\/strong> enums could be tricky?) <\/p>\n<p>Next, the setter updates the state based on both the provided value and current state. If the value already exists in <strong>DogProperties<\/strong><strong>,<\/strong> it is removed, if it doesn&#8217;t exist, it is added. For example, if <strong>DogProperties<\/strong> already included <strong>DogProperties.Big<\/strong>, then you can remove it by reapplying this value to the view-model. This behavior seems odd, but it allows databound XAML controls to effortlessly flip a specific <strong>DogProperty<\/strong>s&#8217; attribute between <strong>true<\/strong> and <strong>false<\/strong> values. <\/p>\n<p>Building <strong>MainWindow<\/strong> is the last implementation task. With all the ground-work complete, then coding proceeds like many other view-models&#8217; views so we need not discuss it in detail. A quick peek at the code-behind, though, reminds us how easy it can be working with <strong>FLAG<\/strong> enumerations, compared with using a bunch of separate properties. <\/p>\n<p class=\"illustration\"><img decoding=\"async\" src=\"https:\/\/www.red-gate.com\/simple-talk\/wp-content\/uploads\/imported\/1591-Xaml%20Code%20Behind-813dfed2-672d-4721-8e00-43bbac5932f9.PNG\" alt=\"1591-Xaml%20Code%20Behind-813dfed2-672d-\" \/><\/p>\n<h3>Lessons from the Field<\/h3>\n<p>It is not exactly easy to Implement <strong>FLAG<\/strong> enumerated values in the real world. The task is not without challenges. Yet, there are also some advantages. <\/p>\n<p>Reducing the property count is by far the biggest positive result of <strong>FLAG<\/strong> enumerated class properties. One integer property serializes quicker and smaller than several Boolean properties. And, as a result, they move over the wire faster and take up less space in a database. <\/p>\n<p>Reducing the property count is by far the biggest downside of <strong>FLAG<\/strong> enumerated class properties. It requires complex or custom code to manipulate them, and this can easily translate into bugs. For example, writing SQL for updating an integer column that equates to several Boolean combinations is not a trivial set operation. <\/p>\n<p>Many .NET developers have not worked <strong>FLAG<\/strong> enumerations. While our Demonstration solution may help to flatten the learning curve, be prepared to show n&#8217; tell the flag. <\/p>\n<p>It isn&#8217;t that easy to introduce extension methods into an application according to the blogosphere. Most of these issues can be avoiding with a few patterns. Firstly, create generic <strong>FLAG<\/strong> enumeration helpers with caution; best targeting them to specific enums. Second, keep extensions &#8220;near&#8221; their enums. If developers can add a reference to an enum without the supporting extension methods, then they are unlikely to use them (until after code reviews). <\/p>\n<p>Finally,&#160;try to avoid using a <strong>FLAG<\/strong> enumeration as a grab-bag of unrelated properties. You can, but you shouldn&#8217;t. Our approach certainly supports this design choice but the mishmash will confuse developers. Would you want to write XAML binding a dozen logically unrelated controls to one property entitled Stuff? <\/p>\n<h2>Conclusion<\/h2>\n<p>This article discussed a set of ideas for implementing flag enumerations within a WPF application using view-models. Many technical and architectural variations exist. For example, I recently saw an application cleverly exploiting an <a href=\"http:\/\/msdn.microsoft.com\/en-us\/library\/system.windows.data.imultivalueconverter.aspx\">IMultiValueConverter<\/a> class instead of IValueConverter for passing enumerations between view and view-model. <\/p>\n<p>Whether or not you incorporate flag enumerations into your next XAML application remains just another one of your many design options. I do hope though after reading this article that one of those decisions just got a little easier. <\/p>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Enums in .NET are strongly-typed constants that allow you to share a multi-valued property across applications. When used in a XAML application with  view-models  it can provide a design choice that greatly simplifies the handling of related boolean attributes. &hellip;<\/p>\n","protected":false},"author":200451,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"_acf_changed":false,"footnotes":""},"categories":[143538],"tags":[4143,4229,5750,5749,4714],"coauthors":[],"class_list":["post-1434","post","type-post","status-publish","format-standard","hentry","category-dotnet-development","tag-net","tag-net-framework","tag-flags","tag-view-models","tag-xaml"],"acf":[],"_links":{"self":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1434","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/users\/200451"}],"replies":[{"embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/comments?post=1434"}],"version-history":[{"count":3,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1434\/revisions"}],"predecessor-version":[{"id":91100,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/posts\/1434\/revisions\/91100"}],"wp:attachment":[{"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/media?parent=1434"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/categories?post=1434"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/tags?post=1434"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.red-gate.com\/simple-talk\/wp-json\/wp\/v2\/coauthors?post=1434"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}