WPF(MVVM)菜单中的互斥(可绑定)复选框 [英] Mutually exclusive (and bindable) checkboxes in menu in WPF (MVVM)

查看:82
本文介绍了WPF(MVVM)菜单中的互斥(可绑定)复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在WPF MVVM应用程序的菜单中查找使用复选框的示例,该复选框可以绑定到基础ViewModel类中的枚举.我有一个简单的例子:

I am trying to find an example of using checkboxes in a menu in a WPF MVVM application that can bind to an enum in the underlying ViewModel Class. I have as a simple example:

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属性设置为蓝色",然后将检查更改为蓝色". 我发现了一些有希望的链接: 相互排斥的可检查菜单项? 如何将RadioButtons绑定到枚举?

I would like to have some XAML (and if necessary a minimal amount of code bind, converters, etc.) that allows the user to pick a menu item "Colors" and see Red, Green, Blue with Red checked (at beginning). Checking Blue would set the MyChosenColor property to Blue and change the check to Blue. I have found some promising links: Mutually exclusive checkable menu items? How to bind RadioButtons to an enum?

但它们似乎都无法处理所有问题(互斥的复选框;复选框,而不是单选按钮),并且许多问题都涉及很多代码.我使用的是Visual Studio 2012,所以也许现在有更好的方法或我忽略了的东西?

but none of them seem to deal with all of the issues (mutually exclusive checkboxes; checkboxes, not radio buttons) and many involve much code behind. I am on Visual Studio 2012 so perhaps there are better methods by now or something I have overlooked?

我必须认为绑定到枚举的菜单中的互斥复选框的想法最常见. 谢谢.

I have to think the idea of mutual exclusive checkboxes in a menu bound to an enum most be a common idea. Thanks.

推荐答案

由于雷切尔(Rachel)的评论,我在下面提出了答案.我希望它可以帮助需要这样做的人.我四处搜寻,但没有看到明确写下的示例.也许这太简单了:)我发现把所有东西放在一起,工作起来有些痛苦,所以我在这里写下来.再次感谢雷切尔!

Thanks to the comments from Rachel, I propose the answer below. I hope it helps someone that needs to do this. I searched around, and did not see an example explicitly written down. Perhaps it's too simple to bother :) I found getting everything pulled together and working somewhat painful, so I'm writing it down here. Thanks again 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代码:

and here is the ViewModel Code:

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
}

您可以在 http://msdn上获取有关RelayCommand和ViewModelBase类的信息. .microsoft.com/en-us/magazine/dd419663.aspx http ://rachel53461.wordpress.com/2011/05/08/simplemvvmexample/

这篇关于WPF(MVVM)菜单中的互斥(可绑定)复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆