in

Dé specialist in .NET trainingen en consultancy

Thomas Huijer

Compile-time checked region names in Prism

In a R&D project of mine, I’m using Prism to create a composite WPF application. I can recommend anyone writing WPF or Silverlight applications to take a look at it if you’re unfamiliair with Prism.

One thing I dislike about it though, is that is uses strings as region names. Meaning that there’s no compile-time checking if your region names in the Shell and the names you’re using when registering the views are actually aligned.

Here’s a small trick to get compile-time checking for your region names in Prism:

  1. Define an Enum containing the names of all known regions:

        public enum RegionName
        {
            ToolBar,
            MessageList,
            Details
        }

  2. Define a MarkupExtension for each value of the enum. This sounds like a lot of work, but with a base class like the one below, it’s no more than a few lines.

        public class BaseRegionExtension : MarkupExtension
        {
            private RegionName _regionName;
     
            public BaseRegionExtension(RegionName regionName)
            {
                _regionName = regionName;
            }
     
            public override object ProvideValue(IServiceProvider serviceProvider)
            {
                return _regionName.ToString();
            }
     
            public RegionName Name
            {
                get
                {
                    return _regionName;
                }
                set
                {
                    _regionName = value;
                }
            }


    Defining a MarkupExtension now becomes really simple:

       public class ToolBarRegionExtension : BaseRegionExtension
        {
            public ToolBarRegionExtension()
                : base(RegionName.ToolBar)
            {
            }
        }

  3. When registering your view, just call the ToString() of the enum value you want to use:

      _regionManager.RegisterViewWithRegion(RegionName.ToolBar.ToString(), typeof(MainToolbarView));

  4. When defining regions in your Shell Xaml file, use the right MarkupExtension to reference a value in your enum:

    <ToolBarPanel>
         <ItemsControl cal:RegionManager.RegionName="{ui:ToolBarRegion}">           
         </ItemsControl>
    </ToolBarPanel>

Have fun!

Comments

No Comments

About Thomas

Thomas is a senior consultant and trainer. He's interested in anything related to improving software quality like clean code, testability, process optimalization, architectures and developer tools. Thomas can be reached at thomas@oosterkamp.nl.