Wpf 对复选框执行命令。已选中或未选中

Wpf 对复选框执行命令。已选中或未选中,wpf,mvvm,checkbox,command,Wpf,Mvvm,Checkbox,Command,我在窗口上有一个复选框控件。我想执行一个命令,该命令将调用关联视图模型中的方法。我还需要复选框的值。我似乎找不到将命令与复选框相关联的方法。有人这样做过吗? <CheckBox Content="CheckBox" Command="{Binding YourCommand}" CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Self}}" /> 这将满

我在窗口上有一个复选框控件。我想执行一个命令,该命令将调用关联视图模型中的方法。我还需要复选框的值。我似乎找不到将命令与复选框相关联的方法。有人这样做过吗?


<CheckBox Content="CheckBox"
          Command="{Binding YourCommand}"
          CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Self}}" />

这将满足您的需要-

<CheckBox CommandParameter="{Binding}"
          Command="{Binding DataContext.AddRemovePresetAssignmentCommand,
          RelativeSource={RelativeSource FindAncestor,
                           AncestorType={x:Type UserControl}}}"
          Content="{Binding Path=Name}">

如果使用MVVM,可以使用如下事件触发器:

<CheckBox IsChecked="{Binding ServiceOrderItemTask.IsCompleted, Mode=TwoWay}" Content="{Binding ServiceOption.Name}">

    <i:Interaction.Triggers>
          <i:EventTrigger EventName="Checked">
                 <i:InvokeCommandAction Command="{Binding DataContext.IsCompletedCheckedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type t:RadGridView}}}" CommandParameter="{Binding}"/>
           </i:EventTrigger>

           <i:EventTrigger EventName="Unchecked">
                 <i:InvokeCommandAction Command="{Binding DataContext.IsCompletedUncheckedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type t:RadGridView}}}" CommandParameter="{Binding}"/>
           </i:EventTrigger>
    </i:Interaction.Triggers>


如果只需要复选框的状态(选中或未选中),则不需要参数。使用此代码时,可以检测复选框的状态:

CheckBox box = e.OriginalSource as CheckBox;

if(box.IsChecked.Value)
    DoThis();
else
    DoAnotherMethod();

“e”是命令中的ExecutedRoutedEventArgs参数。您需要box.IsChecked.Value,因为box.IsChecked来自bool类型?

我迟到了。。。我使用了Rohit Vats的答案并得出了这个代码

该示例是一个工作代码摘录,它仅用于帮助理解各个方面。它是一个图钉,可以是活动的,也可以是非活动的,并且使用DelegateCommand。您也可以使用RelayCommand或任何其他类似的类来完成相同的工作

命令:

using System.Windows.Input;

namespace HQ.Wpf.Util.Command
{
    public class StandardCommand
    {
        public static RoutedUICommand PinPropertyGrid = new RoutedUICommand("Pin property grid", "PinPropertyGrid", typeof(StandardCommand));
Xaml:


型号:

public MainWindowViewModel()
{
    CommandPinPropertyGrid = new DelegateCommand<bool>(PinPropertyGrid);
public主窗口视图模型()
{
CommandPinPropertyGrid=新的DelegateCommand(PinPropertyGrid);

//******************************************************************
public DelegateCommand命令pinPropertyGrid{get;private set;}
公共无效PinPropertyGrid(布尔锁定)
{
this.IsPropertyGridPinned=固定;
}
委派命令:

using System;
using System.Windows.Input;

namespace HQ.Wpf.Util.Command
{

    /// <summary>
    /// Represents a command that forwards the <c>Execute</c> and <c>CanExecute</c> calls to specified delegates.
    /// </summary>
    public class DelegateCommand<T> : ICommand
    {

        private readonly Action<T> _executeCallback;
        private readonly Predicate<T> _canExecuteCallback;

        /////////////////////////////////////////////////////////////////////////////////////////////////////
        // OBJECT
        /////////////////////////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// Initializes a new instance of the <see cref="DelegateCommand<T>"/> class.
        /// </summary>
        /// <param name="executeCallback">The execute callback delegate.</param>
        public DelegateCommand(Action<T> executeCallback)
            : this(executeCallback, null)
        {
            // No-op
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="DelegateCommand<T>"/> class.
        /// </summary>
        /// <param name="executeCallback">The execute callback delegate.</param>
        /// <param name="canExecuteCallback">The can execute callback delegate.</param>
        public DelegateCommand(Action<T> executeCallback, Predicate<T> canExecuteCallback)
        {
            if (executeCallback == null)
                throw new ArgumentNullException("executeCallback");

            this._executeCallback = executeCallback;
            this._canExecuteCallback = canExecuteCallback;
        }

        /////////////////////////////////////////////////////////////////////////////////////////////////////
        // INTERFACE IMPLEMENTATION
        /////////////////////////////////////////////////////////////////////////////////////////////////////

        #region ICommand Members

        /// <summary>
        /// Defines the method that determines whether the command can execute in its current state.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to <see langword="null"/>.</param>
        /// <returns>
        /// <c>true</c> if this command can be executed; otherwise, <c>false</c>.
        /// </returns>
        public bool CanExecute(object parameter)
        {
            return (this._canExecuteCallback == null) ? true : this._canExecuteCallback((T)parameter);
        }

        /// <summary>
        /// Occurs when changes occur that affect whether or not the command should execute.
        /// </summary>
        public event EventHandler CanExecuteChanged
        {
            add
            {
                if (this._canExecuteCallback != null)
                    CommandManager.RequerySuggested += value;
            }
            remove
            {
                if (this._canExecuteCallback != null)
                    CommandManager.RequerySuggested -= value;
            }
        }

        /// <summary>
        /// Defines the method to be called when the command is invoked.
        /// </summary>
        /// <param name="parameter">Data used by the command.  If the command does not require data to be passed, this object can be set to <see langword="null"/>.</param>
        public void Execute(object parameter)
        {
            this._executeCallback((T)parameter);
        }

        #endregion // ICommand Members

    }
}
使用系统;
使用System.Windows.Input;
命名空间HQ.Wpf.Util.Command
{
/// 
///表示将Execute和CanExecute调用转发给指定委托的命令。
/// 
公共类DelegateCommand:ICommand
{
私有只读操作_executeCallback;
私有只读谓词_canExecuteCallback;
/////////////////////////////////////////////////////////////////////////////////////////////////////
//反对
/////////////////////////////////////////////////////////////////////////////////////////////////////
/// 
///初始化类的新实例。
/// 
///执行回调委托。
公共DelegateCommand(Action executeCallback)
:此(executeCallback,null)
{
//无操作
}
/// 
///初始化类的新实例。
/// 
///执行回调委托。
///可以执行回调委托。
公共DelegateCommand(Action executeCallback、谓词canExecuteCallback)
{
if(executeCallback==null)
抛出新ArgumentNullException(“executeCallback”);
这._executeCallback=executeCallback;
这。_canExecuteCallback=canExecuteCallback;
}
/////////////////////////////////////////////////////////////////////////////////////////////////////
//接口实现
/////////////////////////////////////////////////////////////////////////////////////////////////////
#区域ICommand成员
/// 
///定义确定命令是否可以在其当前状态下执行的方法。
/// 
///命令使用的数据。如果命令不要求传递数据,则可以将此对象设置为。
/// 
///如果可以执行此命令,则为true;否则为false。
/// 
公共布尔CanExecute(对象参数)
{
返回(this.\u canExecuteCallback==null)?true:this.\u canExecuteCallback((T)参数);
}
/// 
///当发生影响命令是否应执行的更改时发生。
/// 
公共事件事件处理程序CanExecuteChanged
{
添加
{
如果(此.\u canExecuteCallback!=null)
CommandManager.RequerySuggested+=值;
}
去除
{
如果(此.\u canExecuteCallback!=null)
CommandManager.RequerySuggested-=值;
}
}
/// 
///定义调用命令时要调用的方法。
/// 
///命令使用的数据。如果命令不要求传递数据,则可以将此对象设置为。
public void Execute(对象参数)
{
此._executeCallback((T)参数);
}
#endregion//ICommand成员
}
}
  • System.Windows.Interactivity
    添加到项目引用中
  • 添加
    xmlns:i=”http://schemas.microsoft.com/expression/2010/interactivity“
    到您的XAML名称空间
my ViewModel的
SomeBoolProperty
如下所示:

<CheckBox IsChecked="{Binding ServiceOrderItemTask.IsCompleted, Mode=TwoWay}" Content="{Binding ServiceOption.Name}">

    <i:Interaction.Triggers>
          <i:EventTrigger EventName="Checked">
                 <i:InvokeCommandAction Command="{Binding DataContext.IsCompletedCheckedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type t:RadGridView}}}" CommandParameter="{Binding}"/>
           </i:EventTrigger>

           <i:EventTrigger EventName="Unchecked">
                 <i:InvokeCommandAction Command="{Binding DataContext.IsCompletedUncheckedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type t:RadGridView}}}" CommandParameter="{Binding}"/>
           </i:EventTrigger>
    </i:Interaction.Triggers>
private bool\u SomeBoolProperty=false;
公共bool SomeBoolProperty{
get=>\u SomeBoolProperty;
集合{
_SomeBoolProperty=值;
OnPropertyChanged(名称(SomeBoolProperty));
} 
}
我在这里使用RelayCommand作为命令实现

然后,我的ViewModel上的命令如下所示:

<CheckBox IsChecked="{Binding ServiceOrderItemTask.IsCompleted, Mode=TwoWay}" Content="{Binding ServiceOption.Name}">

    <i:Interaction.Triggers>
          <i:EventTrigger EventName="Checked">
                 <i:InvokeCommandAction Command="{Binding DataContext.IsCompletedCheckedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type t:RadGridView}}}" CommandParameter="{Binding}"/>
           </i:EventTrigger>

           <i:EventTrigger EventName="Unchecked">
                 <i:InvokeCommandAction Command="{Binding DataContext.IsCompletedUncheckedCommand, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type t:RadGridView}}}" CommandParameter="{Binding}"/>
           </i:EventTrigger>
    </i:Interaction.Triggers>
public ICommand MyOnCheckedCommand{get;}=newrelaycommand(o=>{
//做
<CheckBox IsChecked="{Binding SomeBoolProperty, Mode=OneWay}" Content="Check Meee!">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Checked">
            <i:InvokeCommandAction Command="{Binding MyOnCheckedCommand}"/>
        </i:EventTrigger>
        <i:EventTrigger EventName="Unchecked">
            <i:InvokeCommandAction Command="{Binding MyOnUncheckedCommand}"/>
        </i:EventTrigger>
    </i:Interaction.Triggers>
</CheckBox>