WPF - Assign Enum Value To Prism's RegionName Directly

Viewed 42

I am using Prism, this is a chunk of .xaml code of the main window

<mah:MetroWindow
    x:Class="ProjectName.Views.MainWindow"
    xmlns:mah="http://metro.mahapps.com/winfx/xaml/controls"
    xmlns:prism="http://prismlibrary.com/">
        
    <ContentControl
        prism:RegionManager.RegionName="CenterRegion" />
        
</mah:MetroWindow>

I have grouped all regions' names in an Enum UiRegion, And now, I want to rename some of the values in UiRegion, but renaming will not affect the strings in .xaml! Hence, I have to change them manually.. So I've tried to change the .xaml code to something like this

<ContentControl
    prism:RegionManager.RegionName="{x:Static model:UiRegion.CenterRegion}" />

But it gives a runtime error at InitializeComponent();

'CenterRegion' is not a valid value for property 'RegionName'.

My Question is: Is there a way to fix this? and if not, is there another way to update .xaml code when renaming UiRegion values?

3 Answers

I am not using Prism, but I will assume that the RegionName property is of type String. But you want to assign an Enum value to a string. x:Static (just like StaticResource and DynamicResource) does not perform type conversion. To convert, you need to use Binding.
I think the assignment will happen without error if done like this:

<ContentControl
    prism:RegionManager.RegionName="{Binding Source={x:Static model:UiRegion.CenterRegion}}" />

I was working on deriving the RegionManager to add a property of type UiRegion and pass the value of x:Static it to the original property.

It's better to create a markup extension:

    [MarkupExtensionReturnType(typeof(string))]
    public class UiRegionExtension : MarkupExtension
    {
        public UiRegion UiRegion { get; set; }

        public UiRegionExtension(UiRegion uiRegion)
        {
            UiRegion = uiRegion;
        }

        public UiRegionExtension() { }

        public override object ProvideValue(IServiceProvider serviceProvider)
        {
            return UiRegion.ToString();
        }
    }
<ContentControl
    prism:RegionManager.RegionName="{m_ext:UiRegion CenterRegion}"/>

classes do work, too:

code:

public static class RegionNames
{
    public const string MAIN_REGION = "mainregion";
    public const string DETAILS_REGION = "someotherfunnyidentifier";
}

xaml:

<ContentControl prism:RegionManager.RegionName="{x:Static constants:RegionNames.MAIN_REGION}" />
Related