XAML - using a constant in place of a string


XAML - using a constant in place of a string

To keep code consistent, it can be useful to use constants rather than 'magic strings'.


Here is how XAML can be changed, to refer to a constant, rather that to a string:

1. create a C# class, that contains the string constant:

 public class MyConstants  
 {  
   public const string ContentRegion = "ContentRegion";  
 }  


2. In the XAML, add a namespace, to the Assembly and Namespace, that contains the class:

 <window 
...
...
xmlns:inf="namespace=MyApp.Infrastructure;assembly=MyApp.InfrastructureLibrary"
>

where:
a. the C# class is in the namespace: MyApp.Infrastructure
b. the C# class is in the assembly MyApp.InfrastructureLibrary


3. Now in XAML, instead of using a 'magic string':

 < ... prism:RegionManager.RegionName="ContentRegion" />  


you can reference the constant string:

 < ... prism:RegionManager.RegionName="{x:Static inf:MyConstants.ContentRegion}" />  


This should help to keep the code consistent and maintainable.

note: I got this tip, from the http://www.pluralsight.com intro to Prism.

Comments