Friday, September 11, 2015

WPF/Prism using C# strings in Xaml to name Regions

The MVVM design pattern in WPF is often implemented using Prism. In such an implication Views (UserControls) are mapped to regions within WPF pages. Each region is named and all too often said region name is hard coded -- bad programming style.  An example of such is the following excerpt from Shell.xaml where the Prism region is specified as follows:
prsm:RegionManager.RegionName="MainRegion"

The entire Shell.xaml is as follows with the region control noted in boldface:

<Window x:Class=Desktop.Shell"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc=
   "http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:prsm="http://www.codeplex.com/prism"
        xmlns:local="clr-namespace:Desktop"              
        mc:Ignorable="d"
        Title="Any Title Here" Height="350" Width="525"
        TextBlock.TextAlignment="Center">
    <Grid>
        <ContentControl Name="MainRegion" 
             prsm:RegionManager.RegionName="MainRegion" />
    </Grid>
</Window>

A static resource can be used WPF page's title or the content of a TextBlock so why not in the RegionName of a Prism region? Below is the same Shell.xaml modified to reference a C# namespace/assembly and then using the namespace to access a string constant that specifies the region name:

<Window x:Class=Desktop.Shell"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc=
   "http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:prsm="http://www.codeplex.com/prism"
        xmlns:local="clr-namespace:Desktop" 
        xmlns:infrastructure=
"clr-namespace:ViewModels.Infrastructure;assembly=ViewModels"             mc:Ignorable="d"
        Title="Any Title Here" Height="350" Width="525"
        TextBlock.TextAlignment="Center">
    <Grid>
        <ContentControl Name="MainRegion" 
            prsm:RegionManager.RegionName=
              "{x:Static infrastructure:Regions.MainRegion}" />
    </Grid>
</Window>

The C# variable bound to the RegionName is as follows (in boldface):

namespace ViewModels.Infrastructure
{
    public static class Regions
    {
        public const string MainRegion = "MainRegion";

Just because Xaml is markup language and not C# does not mean we should abandon good programming practices. 



No comments :

Post a Comment