2011-04-06 2 views
30

창에 체크 상자 컨트롤이 있습니다. 연결된 뷰 모델에서 메서드를 호출하는 명령을 실행하고 싶습니다. 나는 또한 체크 박스의 가치를 필요로 할 것이다. 명령과 체크 상자를 연결하는 방법을 찾지 못하는 것 같습니다. 아무도이 짓을 한거야?Checkbox.Checked 또는 Unchecked에서 명령 실행

+0

그냥이 링크를 보라 http://stackoverflow.com/questions/959431/how-do-i-attach-commands-to-the-checking-and-unchecking-of- a-checkbox –

답변

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

... RelativeSource.Self를 사용하여 CheckBox의 값에 CommandParameter를 바인딩합니다. –

+27

... 'CommandParameter = "{바인딩 IsChecked, RelativeSource = {RelativeSource Self}, Mode = OneWay}를 사용하여 CommandParameter를 CheckBox의 값에 바인딩합니다.' – Wally

+0

I 명령이 ICommand를 구현해야한다고 가정하십시오. 그것은 저를 위해 일했습니다 (나는 다른 것을 시도하지 않았습니다). –

9

이것은 당신이 필요로 무엇을 작동합니다 -

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

당신이 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> 

+4

우수하지만 이를 사용하려면 XAML에서 다음 네임 스페이스가 필요합니다. 'xmlns : t = "http://schemas.telerik.com/2008/xaml/presentation" "xmlns : i ="http://schemas.microsoft.co.kr/expression/2010/interactivity " ' –

+0

어떻게 viewmodel에서 구현됩니까? – gts13

-2

당신 만이 필요한 경우 CheckBox의 상태 (Checked 또는 Unchecked)는 매개 변수가 필요하지 않습니다.

CheckBox box = e.OriginalSource as CheckBox; 

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

"E"는 명령에 ExecutedRoutedEventArgs - 매개 변수 :이 코드를 사용할 때 체크 박스의 상태를 감지 할 수 있습니다. 너 필요 상자. 확인 됐어. 값, 상자 때문이야. 확인 됐어?

0

나는 늦었습니다 ... 나는 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 

    } 
}