如何将UserControl.IsEnabled绑定到其Command

时间:2013-04-16 13:04:32

标签: c# wpf

我有一个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绑定到命令的可用性?

2 个答案:

答案 0 :(得分: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);
    }

答案 1 :(得分: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);
  }
}