将选中的菜单项绑定到ViewModel命令

时间:2021-05-30 20:21:19

I have in XAML 3 menu items defined (using WPF-MDI):

我在XAML 3中定义了菜单项(使用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:

以及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):

我有2个问题(希望在一个帖子中允许):

  1. 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.
  2. 我想将XAML中的IsChecked属性绑定到所选的值(_selectedTheme)。我想我需要写一个转换器,但我不知道如何。
  3. 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?
  4. 我制作了3份ICommands(每个主题一个)...如果我有20个主题怎么办...有没有办法让这个代码参数化?

Thanks in advance.

提前致谢。

1 个解决方案

#1


5  

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.

没有必要参数化命令,因为绑定将执行所有操作,但如上所述,可以使用CommandParameter。这里转换器将获得枚举参数。

An example:

一个例子:

<MenuItem Header="_Description" IsCheckable="True"
        IsChecked="{Binding Path=DisplayMode_Current,
                            Converter={StaticResource EnumToBooleanConv},
                            ConverterParameter=Description}" />
<MenuItem Header="_Web-Page" IsCheckable="True"
        IsChecked="{Binding Path=DisplayMode_Current,
                            Converter={StaticResource EnumToBooleanConv},
                            ConverterParameter=WebPage}" />

The converter can look something like this:

转换器看起来像这样:

public class EnumToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // You could also directly pass an enum value using {x:Static},
        // then there is no need to parse
        string parameterString = parameter as string;
        if (parameterString == null)
            return DependencyProperty.UnsetValue;

        if (Enum.IsDefined(value.GetType(), value) == false)
            return DependencyProperty.UnsetValue;

        object parameterValue = Enum.Parse(value.GetType(), parameterString);

        return parameterValue.Equals(value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string parameterString = parameter as string;
        if (parameterString == null)
            return DependencyProperty.UnsetValue;

        return Enum.Parse(targetType, parameterString);
    }
}

As the XAML is still verbose (and redundant!) you could take it further by binding the ItemsSource of the parent MenuItem to the enum values and then work with the ItemTemplate and ItemContainerStyle.

由于XAML仍然冗长(并且冗余!),您可以通过将父MenuItem的ItemsSource绑定到枚举值来进一步使用它,然后使用ItemTemplate和ItemContainerStyle。

#1


5  

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.

没有必要参数化命令,因为绑定将执行所有操作,但如上所述,可以使用CommandParameter。这里转换器将获得枚举参数。

An example:

一个例子:

<MenuItem Header="_Description" IsCheckable="True"
        IsChecked="{Binding Path=DisplayMode_Current,
                            Converter={StaticResource EnumToBooleanConv},
                            ConverterParameter=Description}" />
<MenuItem Header="_Web-Page" IsCheckable="True"
        IsChecked="{Binding Path=DisplayMode_Current,
                            Converter={StaticResource EnumToBooleanConv},
                            ConverterParameter=WebPage}" />

The converter can look something like this:

转换器看起来像这样:

public class EnumToBooleanConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // You could also directly pass an enum value using {x:Static},
        // then there is no need to parse
        string parameterString = parameter as string;
        if (parameterString == null)
            return DependencyProperty.UnsetValue;

        if (Enum.IsDefined(value.GetType(), value) == false)
            return DependencyProperty.UnsetValue;

        object parameterValue = Enum.Parse(value.GetType(), parameterString);

        return parameterValue.Equals(value);
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        string parameterString = parameter as string;
        if (parameterString == null)
            return DependencyProperty.UnsetValue;

        return Enum.Parse(targetType, parameterString);
    }
}

As the XAML is still verbose (and redundant!) you could take it further by binding the ItemsSource of the parent MenuItem to the enum values and then work with the ItemTemplate and ItemContainerStyle.

由于XAML仍然冗长(并且冗余!),您可以通过将父MenuItem的ItemsSource绑定到枚举值来进一步使用它,然后使用ItemTemplate和ItemContainerStyle。