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 回答