Подтвердить что ты не робот

Выполнение команды в Checkbox.Checked или Unchecked

У меня есть флажок в окне. Я хотел бы выполнить команду, которая вызовет метод в связанной модели представления. Мне также понадобится значение флажка. Кажется, я не могу найти способ связать команду с помощью флажка. Кто-нибудь сделал это?

4b9b3361

Ответ 1

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

Ответ 2

Если вы используете 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>

Ответ 3

Это будет работать, что вам нужно -

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

Ответ 4

Я опаздываю... Я использовал 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:

                            <CheckBox HorizontalAlignment="Right" 
                                      VerticalAlignment="Top"
                                      Margin="2,0,3,0" 
                                      Command="{Binding CommandPinPropertyGrid}"
                                      CommandParameter="{Binding IsChecked, RelativeSource={RelativeSource Self}}">
                                <CheckBox.Template>
                                    <ControlTemplate TargetType="{x:Type CheckBox}">
                                        <Grid>
                                            <Image x:Name="ImagePushpin" Width="16" Height="16" Source="pack://application:,,,/WpfUtil;component/Images/PushpinUnpinned16x16.png" />
                                        </Grid>
                                        <ControlTemplate.Triggers>
                                            <Trigger Property="IsChecked" Value="True">
                                                <Setter TargetName="ImagePushpin" Property="Source" Value="pack://application:,,,/WpfUtil;component/Images/PushpinPinned16x16.png" />
                                            </Trigger>
                                        </ControlTemplate.Triggers>
                                    </ControlTemplate>
                                </CheckBox.Template>
                            </CheckBox>

Модель:

public MainWindowViewModel()
{
    CommandPinPropertyGrid = new DelegateCommand<bool>(PinPropertyGrid);

...

// ******************************************************************
public DelegateCommand<bool> CommandPinPropertyGrid { get; private set; }

public void PinPropertyGrid(bool pinned)
{
    this.IsPropertyGridPinned = pinned;
}

DelegateCommand:

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

    }
}

Ответ 5

  • Добавьте System.Windows.Interactivity к ссылкам вашего проекта.
  • Добавьте xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" в свои пространства имен XAML.
<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>

Я реализую INotifyPropertyChanged в моей ViewModel следующим образом:

public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name) => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));

SomeBoolProperty моей ViewModel выглядит следующим образом:

private bool _SomeBoolProperty = false;
public bool SomeBoolProperty { 
    get => _SomeBoolProperty;
    set { 
        _SomeBoolProperty = value; 
        OnPropertyChanged(nameof(SomeBoolProperty)); 
    } 
}

Я использую RelayCommand в качестве моей реализации команды отсюда fooobar.com/questions/238856/....

Команды на моей ViewModel выглядят так:

public ICommand MyOnCheckedCommand { get; } = new RelayCommand(o => {
    // Do something here.
    SomeBoolProperty = true;
});
public ICommand MyOnUncheckedCommand { get; } = new RelayCommand(o => {
    // Do something else here.
    SomeBoolProperty = false;
});

Я добрался до этого вопроса, пытаясь найти способ повторно использовать две команды, которые у меня уже были в моей ViewModel. Один звонил, когда проверял, и один, когда не проверял. Я использую их на некоторых кнопках, поэтому не хотел добавлять дополнительную параметризованную команду. Люди спрашивали здесь о реализации ViewModel, поэтому добавьте этот ответ, чтобы завершить ответ от Igor_S. Надеюсь, это поможет.

Ответ 6

Если вам нужен только статус CheckBox (Checked or Unchecked), вам не нужен параметр. Вы можете определить статус флажка при использовании этого кода:

CheckBox box = e.OriginalSource as CheckBox;

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

"e" - это параметр ExecutedRoutedEventArgs в команде. Вам нужна box.IsChecked.Value, потому что box.IsChecked - это тип bool?.