【问题标题】:Implementing custom CanExecuteChanged event with Commands in WPF在 WPF 中使用命令实现自定义 CanExecuteChanged 事件
【发布时间】:2010-04-06 08:15:09
【问题描述】:

我尝试为命令按钮执行自定义 CanExecuteChanged 事件。在 CanExecuteChanged 事件中,我想在 canExecute 值更改时做一些事情,但我不想通过实现自定义命令按钮类(派生自 Button 并实现 ICommandSource)来实现。我也不想在 CanExecute 方法中做我的事情。

有什么想法吗?

谢谢。

【问题讨论】:

    标签: wpf button command


    【解决方案1】:

    可以处理命令的CanExecuteChanged事件

    【讨论】:

    • 好的,我同意,但是如何处理和实施呢?我想和 Executed 和 CanExecute 方法一样,例如: private void CanExecuteChanged(object sender, EventArgs e) { // Do my stuff } 我的问题是我不知道如何将这个事件绑定到命令按钮。在我的 xaml 我做:
    • 什么是“MyCommand”?它是如何定义的?请编辑您的答案以发布代码:在 cmets 中,它是不可读的
    • 对不起,我已经发布了一个关于我想要做什么的示例。我已将其发布为答案以使其更具可读性。
    • 在 Page 构造函数中,只需将您的 CanExecuteChanged 方法订阅到 MyNameSpace.MyClass.MyRCmd.CanExecuteChanged 事件即可。顺便说一句,您应该编辑原始问题,而不是发布答案。
    • 好的,谢谢!我照你说的做,现在我可以通过执行我的 CanExecuteChanged 的​​自定义处理程序来处理 CanExecute 更改其值的情况;)
    【解决方案2】:

    例如:

    在 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 方法并将其执行。

    非常感谢。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-13
      • 1970-01-01
      • 2011-07-18
      • 2020-07-09
      • 2010-12-26
      • 1970-01-01
      • 1970-01-01
      • 2011-08-31
      相关资源
      最近更新 更多