3

コマンドを宣言する UserControl があります。

public static readonly DependencyProperty CommandProperty = 
    DependencyProperty.Register("Command", typeof(ICommand), typeof(MyUserControl));

public ICommand Command
{
    get { return (ICommand) GetValue(CommandProperty); }
    set { SetValue(CommandProperty, value); }
}

コマンドは親 UI によって割り当てられます。
UserControl の IsEnabled をコマンドの可用性にバインドするにはどうすればよいですか?

4

2 に答える 2

3

これを試して:

 public static readonly DependencyProperty CommandProperty =
        DependencyProperty.Register("Command", typeof(ICommand), typeof(UserControl1),
                                    new PropertyMetadata(default(ICommand), OnCommandChanged));

    public ICommand Command
    {
        get { return (ICommand) GetValue(CommandProperty); }
        set { SetValue(CommandProperty, value); }
    }

    private static void OnCommandChanged(DependencyObject dependencyObject,
                                         DependencyPropertyChangedEventArgs dependencyPropertyChangedEventArgs)
    {
        var userControl = (UserControl1) dependencyObject;
        var command = dependencyPropertyChangedEventArgs.OldValue as ICommand;
        if (command != null)
            command.CanExecuteChanged -= userControl.CommandOnCanExecuteChanged;
        command = dependencyPropertyChangedEventArgs.NewValue as ICommand;
        if (command != null)
            command.CanExecuteChanged += userControl.CommandOnCanExecuteChanged;
    }

    private void CommandOnCanExecuteChanged(object sender, EventArgs eventArgs)
    {
        IsEnabled = ((ICommand) sender).CanExecute(null);
    }
于 2013-04-16T13:44:51.843 に答える
1

これを試すことができます:

public static readonly DependencyProperty CommandProperty =
  DependencyProperty.Register(
    "Command", typeof(ICommand), typeof(UserControl1), new PropertyMetadata(null, OnCurrentCommandChanged));

private static void OnCurrentCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
  UserControl1 currentUserControl = d as UserControl1;
  ICommand newCommand = e.NewValue as ICommand;
  if (currentUserControl == null || newCommand == null)
    return;
  newCommand.CanExecuteChanged += (o, args) => currentUserControl.IsEnabled = newCommand.CanExecute(null);
}

public ICommand Command {
  get {
    return (ICommand)GetValue(CommandProperty);
  }
  set {
    SetValue(CommandProperty, value);
  }
}
于 2013-04-16T13:44:17.043 に答える