【问题标题】:WPF RoutedCommand CanExecute event is not fired未触发 WPF RoutedCommand CanExecute 事件
【发布时间】:2015-03-24 20:32:28
【问题描述】:

我创建了一个用户控件,里面有一个命令 (DeleteCommand):

public partial class TestControl : UserControl
{
    public static RoutedCommand DeleteCommand = new RoutedCommand();
    private void DeleteCommandExecute(object sender, ExecutedRoutedEventArgs e)
    {

    }
    private void DeleteCommandCanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }



    public TestControl()
    {
        InitializeComponent();
        CommandBinding deleteCommandBinding = new CommandBinding(DeleteCommand, DeleteCommandExecute, DeleteCommandCanExecute);
            this.CommandBindings.Add(deleteCommandBinding);
    }
}

我已经把这个 UserControl 放在了一个窗口中:

<Window x:Class="TestRoutedCommand.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:TestRoutedCommand"
    Title="MainWindow" Height="350" Width="525">

    <Grid>
        <Button Content="Fire event" Margin="156,29,205,254" Command="{x:Static local:TestControl.DeleteCommand}" />        
        <local:TestControl Margin="126,135,135,46"/>        
    </Grid>
</Window>

还有一个使用 DeleteCommand 的按钮。我的问题是这个按钮总是被禁用并且永远不会调用 DeleteCommandCanExecute 处理程序,尽管 e.CanExecute 总是设置为 true。

我试过打电话:

CommandManager.InvalidateRequerySuggested();

但什么也没发生。该事件永远不会被触发。也许我做错了 CommandBinding。

我想要实现的是,当用户单击按钮时,DeleteCommandExecute 处理程序被触发。我的目标是为我的 MenuButtons 创建命令,这将触发我的 UserControls 中的一些方法,这些方法可能在 Visual Tree 的深处。

【问题讨论】:

  • 如果您的命令是静态的,您是否尝试过将 DeleteCommandExecute 和 DeleteCommandCanExecute 也切换为静态?
  • 尝试让 DeleteCommand 成为一个属性,而不仅仅是一个成员变量?
  • 为什么用户控件中有命令?您通常会在视图模型中有一个命令,您可以在其中使用像 RelayCommand 这样的辅助类来实现它。

标签: c# wpf xaml command


【解决方案1】:

稍微更改您的 XAML:

<Grid>
    <Button Content="Fire event" Margin="156,29,205,254" Command="{x:Static local:TestControl.DeleteCommand}" CommandTarget="{Binding ElementName=Control1}" />        
    <local:TestControl x:Name="Control1" Margin="126,135,135,46"/>        
</Grid>

CommandTarget 说明在哪里可以找到所需的处理程序。

【讨论】:

  • 是的,但我必须在 UserControl 中触发 Execute。您的解决方案等于绑定到按钮的 Click EventHandler
  • 好的,我换个方案
  • 但是如果 UserControl 在可视化树中更深怎么办?可以说,UserControl 中的 UserControl,并且 Child UserControl 需要触发 Execute 事件
  • 你只需要链接来控制。可以在 .cs 代码(属性)中:button.Command = TestControl.DeleteCommand;button.CommandTarget=link; 视情况而定,但在可视化树中找到您的控件也可以。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-12-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多