我试图在自定义控件上实现ICommandSource(类似于按钮)。目前这个实现大部分就像在ICommandSource的msdn页面上显示的一样,并且在ButtonBase源代码中显示。在属性更改上重新评估CanExecute
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}
什么属性更改? – user195275
其INotifyChangedProperty – Bambu