【发布时间】:2010-04-06 08:15:09
【问题描述】:
我尝试为命令按钮执行自定义 CanExecuteChanged 事件。在 CanExecuteChanged 事件中,我想在 canExecute 值更改时做一些事情,但我不想通过实现自定义命令按钮类(派生自 Button 并实现 ICommandSource)来实现。我也不想在 CanExecute 方法中做我的事情。
有什么想法吗?
谢谢。
【问题讨论】:
我尝试为命令按钮执行自定义 CanExecuteChanged 事件。在 CanExecuteChanged 事件中,我想在 canExecute 值更改时做一些事情,但我不想通过实现自定义命令按钮类(派生自 Button 并实现 ICommandSource)来实现。我也不想在 CanExecute 方法中做我的事情。
有什么想法吗?
谢谢。
【问题讨论】:
可以处理命令的CanExecuteChanged事件
【讨论】:
CanExecuteChanged 方法订阅到 MyNameSpace.MyClass.MyRCmd.CanExecuteChanged 事件即可。顺便说一句,您应该编辑原始问题,而不是发布答案。
例如:
在 XAML 中:
<Page xmlns:local="clr-namespace:MySolution" ....>
<Page.CommandBindings>
<CommandBinding Command="{x:Static local:MyNameSpace.MyClass.MyRCmd}"
Executed="MyCmdBinding_Executed"
CanExecute="MyCmdBinding_CanExecute"/>
</Page.CommandBindings>
...
<Button Command="{x:Static local:MyNameSpace.MyClass.MyRCmd}" ... />
...
</Page>
在页面代码后面:
namespace MyNameSpace
{
public partial class MyClass : Page
{
...
public static RoutedCommand MyRCmd = new RoutedCommand();
public event EventHandler CanExecuteChanged;
private void CanExecuteChanged(object sender, EventArgs e)
{
// Here is my problem: How to say to execute this when CanExecute value is
// changing? I would like to execute this on CanExecute value changed.
// I think somewhere I can tell compiler the handler for CanExecutedChanged is
// this. How to?
}
private void MyCmdBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
// Do my stuff when CanExecute is true
}
private void MyCmdBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
if (....)
{
e.CanExecute = true;
}
else
{
e.CanExecute = false;
}
}
...
} // end class
} // end namespace
我的问题是如何说编译器:嘿,在 CanExecute 值发生更改时,您必须调用 CanExecuteChanged 方法并将其执行。
非常感谢。
【讨论】: