如何绑定UserControl.IsEnabled to its Command
本文关键字:IsEnabled to its Command UserControl 何绑定 绑定 | 更新日期: 2023-09-27 18:09:39
我有一个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); }
}
父用户界面分配的命令。
我如何将UserControl的IsEnabled绑定到命令的可用性?
试试这个:
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);
}
你可以试试:
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);
}
}