WPF(MVVM)菜单中互斥(且可绑定)复选框

4

我正在尝试找到一个在WPF MVVM应用程序中使用复选框作为菜单并可以绑定到基础ViewModel类中的枚举的示例。下面是一个简单的示例:

public class MyViewModel
{

   public MyViewModel() // constructor
   {
      MyChosenColor = Colors.Red;  // Pick red by default...
   }
   public enum Colors
   {
      Red,
      Green,
      Blue,   // this is just an example.  Could be many more values...
   }
   public Colors MyChosenColor {get; set;}
}

我希望有一些XAML(如果必要,可以使用一些代码绑定、转换器等)允许用户选择菜单项“颜色”,并且一开始红色项目被选中,界面上显示红色、绿色和蓝色。当用户勾选了“蓝色”后,MyChosenColor属性应该被设置为蓝色,并且在界面上蓝色项目被选中。 我找到了一些不错的链接: Mutually exclusive checkable menu items? How to bind RadioButtons to an enum? 但是,它们都没有解决所有问题(互斥复选框;复选框,而不是单选按钮),而且很多都需要大量的代码。我使用的是Visual Studio 2012,也许现在有更好的方法或者我漏掉了什么?
我认为,在菜单中实现互斥的复选框,绑定至一个枚举类型,这个想法应该是很常见的。 谢谢!

2
我认为你发的第二个链接就是答案。它可以用于复选框,而且包含了你所需要的一切,对吧?除此之外,从用户体验的角度来看,单选按钮可能更常见、更为人所知,用于互斥的内容,而不是复选框。 - stijn
1
感谢您的快速评论,Stijn。我会重新调查第二个链接,但我有一些担忧:(1)对我来说不清楚如何将其适应于菜单的使用,(2)不清楚它是否适用于复选框。示例正是因为他在StackPanel中使用单选按钮而获得了互斥行为,也许最重要的是(3)他硬编码了3个单选按钮,我希望有一个更通用的解决方案(也许是ItemsView、ListView.ItemsPanel或类似的东西?),最后,(4)他没有展示如何将点击结果传递给ViewModel(使用CommandBinding?)。感谢您的评论。 - Dave
好的观点,恐怕我没有仔细阅读你的问题。 - stijn
2
你不能将 Menu.ItemsSource 绑定到一个 ObservableCollection<T> 上吗?其中 <T> 是一个包含 IsChecked 属性的类,可以将其绑定到 MenuItem.IsChecked 上。然后,为集合中的每个项附加一个 PropertyChange 通知,告诉它当 IsChecked 更改为 true 时,将集合中的所有其他项设置为 IsChecked=false - Rachel
谢谢Rachel。我看到了一些暗示这个想法的其他帖子。你能给我一个例子吗?[请以答案的形式发布]我希望有一个更简单的方法。我的意思是,如果从“关注点分离”的角度来看,任何编写项目的ViewModel部分的人都可以采取这种态度,“嘿,我已经做了我需要做的一切(就像上面的例子一样)。为什么我要引入一系列类呢?幸运的是,我是负责所有三个层的程序员,所以我可以让自己在VM层做更多的工作 :)。 - Dave
3个回答

4

感谢Rachel的评论,下面是我的答案。我希望这能帮助那些需要此操作的人。我搜寻了许多,没有发现明确写下的例子。或许这太简单了,不值得去费力 :) 我发现整合所有东西并使其运作起来有些困难,所以在这里记录下来。再次感谢Rachel!

<Window x:Class="Demo.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
     xmlns:local="clr-namespace:Demo"
    Title="MainWindow" Height="350" Width="525">
<Window.Resources>

</Window.Resources>
<DockPanel>
    <Menu DockPanel.Dock="Top">
        <MenuItem Header="Number Of Players"  ItemsSource="{Binding Path=MyCollection}">
            <MenuItem.ItemContainerStyle>
                <Style TargetType="MenuItem">
                    <Setter Property="Header" Value="{Binding Title}" />
                    <Setter Property="IsCheckable" Value="True" />

                    <Setter Property="IsChecked" Value="{Binding IsChecked,Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
                    <Setter Property="Command" Value="{Binding DataContext.MyCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type MenuItem}}}" />
                    <Setter Property="CommandParameter" Value="{Binding Player}" />
                </Style>
            </MenuItem.ItemContainerStyle>


        </MenuItem>

        </Menu>

    <Grid>

</Grid>
</DockPanel>

以下是ViewModel代码:

namespace Demo.ViewModel
{
public class MainViewModel : ViewModelBase
{

    public MainViewModel()
    {
       _myCollection = new ObservableCollection<NumberOfPlayersClass>();
        foreach (NumberOfPlayersEnum value in Enum.GetValues(typeof(NumberOfPlayersEnum)))
        {
            NumberOfPlayersClass myClass = new NumberOfPlayersClass();
            myClass.Player = value;
            myClass.IsChecked = value == NumberOfPlayersEnum.Two ? true : false; // default to using 2 players
            myClass.Title = Enum.GetName(typeof(NumberOfPlayersEnum), value);
            _myCollection.Add(myClass);
        }
    }
    private ICommand _myCommand;
    public ICommand MyCommand
    {
        get
        {
            if (_myCommand == null)
            {
                _myCommand = new RelayCommand(new Action<object>(ResolveCheckBoxes));

            }
            return _myCommand;
        }
    }



    ObservableCollection<NumberOfPlayersClass> _myCollection = new ObservableCollection<NumberOfPlayersClass>();
    public ObservableCollection<NumberOfPlayersClass> MyCollection
    {
        get
        {
           return _myCollection;
        }

    }
    public enum NumberOfPlayersEnum
    {
        One = 1,
        Two =2,
        Three =3,
    }
    public class NumberOfPlayersClass : ViewModelBase
    {
        public NumberOfPlayersClass()
        {
            IsChecked = false;
        }
        public NumberOfPlayersEnum Player { get; set; }
        private bool _isChecked = false;

        public bool IsChecked
        { get 
        { return _isChecked;
        }
            set
            {
                _isChecked = value;
                OnPropertyChanged("IsChecked");
            }

       }
        public string Title { get; set; }

    }

    private void ResolveCheckBoxes(object checkBoxNumber)
    {
        NumberOfPlayersEnum myEnum = (NumberOfPlayersEnum)checkBoxNumber;
        ObservableCollection<NumberOfPlayersClass> collection = MyCollection;
        NumberOfPlayersClass theClass = collection.First<NumberOfPlayersClass>(t => t.Player == myEnum);

            // ok, they want to check this one, let them and uncheck all else
            foreach (NumberOfPlayersClass iter in collection)
            {
                iter.IsChecked = false;
            }
            theClass.IsChecked = true;



    }
}
/// <summary>
/// A command whose sole purpose is to 
/// relay its functionality to other
/// objects by invoking delegates. The
/// default return value for the CanExecute
/// method is 'true'.
/// </summary>
public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    /// <summary>
    /// Creates a new command that can always execute.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    /// <summary>
    /// Creates a new command.
    /// </summary>
    /// <param name="execute">The execution logic.</param>
    /// <param name="canExecute">The execution status logic.</param>
    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }

    #endregion // Constructors

    #region ICommand Members

    [DebuggerStepThrough]
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    #endregion // ICommand Members
}
}

/// <summary>
/// Base class for all ViewModel classes in the application.
/// It provides support for property change notifications 
/// and has a DisplayName property.  This class is abstract.
/// </summary>
public abstract class ViewModelBase : INotifyPropertyChanged, IDisposable
{
    #region Constructor

    protected ViewModelBase()
    {
    }

    #endregion // Constructor

    #region DisplayName

    /// <summary>
    /// Returns the user-friendly name of this object.
    /// Child classes can set this property to a new value,
    /// or override it to determine the value on-demand.
    /// </summary>
    public virtual string DisplayName { get; protected set; }

    #endregion // DisplayName

    #region Debugging Aides

    /// <summary>
    /// Warns the developer if this object does not have
    /// a public property with the specified name. This 
    /// method does not exist in a Release build.
    /// </summary>
    [Conditional("DEBUG")]
    [DebuggerStepThrough]
    public void VerifyPropertyName(string propertyName)
    {
        // Verify that the property name matches a real,  
        // public, instance property on this object.
        if (TypeDescriptor.GetProperties(this)[propertyName] == null)
        {
            string msg = "Invalid property name: " + propertyName;

            if (this.ThrowOnInvalidPropertyName)
                throw new Exception(msg);
            else
                Debug.Fail(msg);
        }
    }

    /// <summary>
    /// Returns whether an exception is thrown, or if a Debug.Fail() is used
    /// when an invalid property name is passed to the VerifyPropertyName method.
    /// The default value is false, but subclasses used by unit tests might 
    /// override this property's getter to return true.
    /// </summary>
    protected virtual bool ThrowOnInvalidPropertyName { get; private set; }

    #endregion // Debugging Aides

    #region INotifyPropertyChanged Members

    /// <summary>
    /// Raised when a property on this object has a new value.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    /// Raises this object's PropertyChanged event.
    /// </summary>
    /// <param name="propertyName">The property that has a new value.</param>
    protected virtual void OnPropertyChanged(string propertyName)
    {
        this.VerifyPropertyName(propertyName);

        PropertyChangedEventHandler handler = this.PropertyChanged;
        if (handler != null)
        {
            var e = new PropertyChangedEventArgs(propertyName);
            handler(this, e);
        }
    }

    #endregion // INotifyPropertyChanged Members

    #region IDisposable Members

    /// <summary>
    /// Invoked when this object is being removed from the application
    /// and will be subject to garbage collection.
    /// </summary>
    public void Dispose()
    {
        this.OnDispose();
    }

    /// <summary>
    /// Child classes can override this method to perform 
    /// clean-up logic, such as removing event handlers.
    /// </summary>
    protected virtual void OnDispose()
    {
    }

#if DEBUG
    /// <summary>
    /// Useful for ensuring that ViewModel objects are properly garbage collected.
    /// </summary>
    ~ViewModelBase()
    {
        string msg = string.Format("{0} ({1}) ({2}) Finalized", this.GetType().Name,      this.DisplayName, this.GetHashCode());
        System.Diagnostics.Debug.WriteLine(msg);
    }
#endif

    #endregion // IDisposable Members
}

你可以在以下网址获取关于RelayCommand和ViewModelBase类的信息:http://msdn.microsoft.com/en-us/magazine/dd419663.aspxhttp://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/

0

this博客文章启发的另一种答案:

class CheckBoxGroup
{
    public static bool GetIsEnabled(DependencyObject obj) => (bool)obj.GetValue(IsEnabledProperty);
    public static void SetIsEnabled(DependencyObject obj, string value) =>
                                                              obj.SetValue(IsEnabledProperty, value);
    public static readonly DependencyProperty IsEnabledProperty = 
         DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(CheckBoxGroup), 
               new PropertyMetadata(false, Callback));

    private static void Callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var container = d as UIElement;
        container.AddHandler(ToggleButton.CheckedEvent, 
                                    new RoutedEventHandler(GroupedButton_Checked));
    }

    private static void GroupedButton_Checked(object sender, RoutedEventArgs e)
    {
        var container = sender as DependencyObject;
        var source = e.OriginalSource as ToggleButton;
        foreach(var child in LogicalTreeHelper.GetChildren(container).OfType<ToggleButton>())
        {
            if(child != source) child.IsChecked = false;
        }
    }
}

使用方法:

<ListBox local:CheckBoxGroup.IsEnabled="True">
    <CheckBox Content="Dibble"/>
    <CheckBox Content="Dobble"/>
    <CheckBox Content="Dabble"/>
    <CheckBox Content="Dubble"/>
</ListBox>

0

请查看我的答案"如何使菜单项互斥选中",其中介绍了一种使用RoutedUICommands、枚举和DataTriggers的方法。这基本上就是您最初所要求的。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接