【发布时间】:2012-10-23 18:53:54
【问题描述】:
我正在尝试在自定义控件(类似于按钮)上实现 ICommandSource。目前的实现主要是显示在 ICommandSource 的 msdn 页面上以及显示在 ButtonBase 源代码中。
CanExecute 在控件加载时触发,但在任何属性发生更改时不会触发。传递给常规按钮的相同命令可以正常工作。当应该更改的属性发生更改时,CanExecute 触发并启用按钮。该命令是一个委托命令。
我已经尝试过 CommandManager.InvalidateRequerySuggested();但这并没有奏效。
有什么想法吗?
这是自定义控件中的实现:
private static void OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
CollapsibleSplitButton csb = (CollapsibleSplitButton)d;
csb.OnCommandChanged((ICommand)e.OldValue, (ICommand)e.NewValue);
}
private void OnCommandChanged(ICommand oldCommand, ICommand newCommand)
{
if (oldCommand != null) UnhookCommand(oldCommand);
if (newCommand != null) HookCommand(newCommand);
}
private void UnhookCommand(ICommand command)
{
command.CanExecuteChanged -= OnCanExecuteChanged;
UpdateCanExecute();
}
private void HookCommand(ICommand command)
{
command.CanExecuteChanged += OnCanExecuteChanged;
UpdateCanExecute();
}
private void OnCanExecuteChanged(object sender, EventArgs e)
{
UpdateCanExecute();
}
private void UpdateCanExecute()
{
if (Command != null)
CanExecute = Command.CanExecute(CommandParameter);
else
CanExecute = true;
}
protected override bool IsEnabledCore
{
get { return base.IsEnabledCore && CanExecute; }
}
我设置命令的地方:
...
MyCommand = new DelegatingCommand(DoStuff, CanDoStuff);
...
private bool CanDoStuff()
{
return (DueDate == null);
}
private void DoStuff() {//do stuff}
【问题讨论】:
-
它是一个 INotifyChangedProperty