I have in XAML 3 menu items defined (using WPF-MDI):
<MenuItem Header="_Generic" Name="Generic" ToolTip="Generic Visual Studio designer theme"
Command="{Binding Path=SelectGenericTheme}"/>
<MenuItem Header="_Luna" Name="Luna" ToolTip="Blue Windows XP theme"
Command="{Binding Path=SelectLunaTheme}"/>
<MenuItem Header="_Aero" Name="Aero" ToolTip="Windows Vista/7 theme"
Command="{Binding Path=SelectAeroTheme}"/>
And the definitions of the commands and current selection in the ViewModel:
public enum ESelectedTheme
{
Generic,
Luna,
Aero
}
ESelectedTheme _selectedTheme;
ICommand _selectGenericThemeCommand;
public ICommand SelectGenericThemeCommand
{
get { return _selectGenericThemeCommand ?? (_selectGenericThemeCommand = new RelayCommand(param => SelectGenericTheme(),
param => true)); }
}
void SelectGenericTheme()
{
_selectedTheme = ESelectedTheme.Generic;
}
ICommand _selectLunaThemeCommand;
public ICommand SelectLunaThemeCommand
{
get
{
return _selectLunaThemeCommand ?? (_selectLunaThemeCommand = new RelayCommand(param => SelectLunaTheme(),
param => true));
}
}
void SelectLunaTheme()
{
_selectedTheme = ESelectedTheme.Luna;
}
ICommand _selectAeroThemeCommand;
public ICommand SelectAeroThemeCommand
{
get
{
return _selectAeroThemeCommand ?? (_selectAeroThemeCommand = new RelayCommand(param => SelectAeroTheme(),
param => true));
}
}
void SelectAeroTheme()
{
_selectedTheme = ESelectedTheme.Aero;
}
I have 2 questions (hope that is allowed inside one post):
- I want to bind the IsChecked property in XAML to the value that is selected (_selectedTheme). I think I need to write a converter but I don’t know how.
- I made 3 copies of ICommands (one for each theme) … what if I would have 20 themes … is there a way to make this code parameterized?
Thanks in advance.
It will not be necessary to parameterize the command as the binding will do everything but as noted it would be possible using
CommandParameter. Here the converter will get the enum parameter.An example:
The converter can look something like this:
As the XAML is still verbose (and redundant!) you could take it further by binding the
ItemsSourceof the parentMenuItemto the enum values and then work with theItemTemplateandItemContainerStyle.