Let me post another option.
Let's say we want a ComboBox
populated with the NavigationViewPaneDisplayMode
enum.
This class will hold the items in the target enum.
public class EnumOptions<T> : ReadOnlyCollection<T> where T : Enum
{
public EnumOptions() : this(Enum.GetValues(typeof(T)).Cast<T>().ToArray())
{
}
private EnumOptions(IList<T> list) : base(list)
{
}
}
We need this class to use EnumOptions<T>
in XAML.
public class NavigationViewPaneDisplayModeOptions : EnumOptions<NavigationViewPaneDisplayMode>
{
}
This class is optional.
public partial class EnumCamelCaseToSpacedStringConverter : IValueConverter
{
public bool OnlyTheFirstWordFirstCharacterIsUpperCase { get; set; }
public object Convert(object value, Type targetType, object parameter, string language)
{
if (value?.ToString() is string stringValue)
{
if (stringValue.Length is 0)
{
return string.Empty;
}
string spacedString = Regex.Replace(stringValue, "(\\B[A-Z])", " $1");
if (OnlyTheFirstWordFirstCharacterIsUpperCase is false)
{
return spacedString;
}
string onlyTheFirstCharacterUpperCase = $"{spacedString[0].ToString()?.ToUpper()}{spacedString.Substring(1).ToLower()}";
return onlyTheFirstCharacterUpperCase;
}
throw new ArgumentException("Value must be a string", nameof(value));
}
public object ConvertBack(object value, Type targetType, object parameter, string language) => throw new NotImplementedException();
}
And we use it like this:
<Page.Resources>
<local:NavigationViewPaneDisplayModeOptions x:Key="NavigationViewPaneDisplayModeOptions" />
<local:EnumCamelCaseToSpacedStringConverter
x:Key="CamelCaseStringConverter"
OnlyTheFirstWordFirstCharacterIsUpperCase="True" />
</Page.Resources>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<ComboBox
x:Name="NavigationViewPaneDisplayModeComboBox"
Grid.Row="0"
ItemsSource="{StaticResource NavigationViewPaneDisplayModeOptions}"
SelectedIndex="0">
<ComboBox.ItemTemplate>
<DataTemplate x:DataType="NavigationViewPaneDisplayMode">
<TextBlock Text="{x:Bind Converter={StaticResource CamelCaseStringConverter}}" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<NavigationView
Grid.Row="1"
PaneDisplayMode="{x:Bind (NavigationViewPaneDisplayMode)NavigationViewPaneDisplayModeComboBox.SelectedValue, Mode=OneWay}">
<NavigationView.MenuItems>
<NavigationViewItem Content="Menu 1" />
<NavigationViewItem Content="Menu 2" />
<NavigationViewItem Content="Menu 3" />
</NavigationView.MenuItems>
</NavigationView>
</Grid>