WPF RoutedCommand CanExecute 事件未触发

WPF RoutedCommand CanExecute event is not fired

我创建了一个用户控件,里面有一个命令 (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:

<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 中的一些方法,这些方法可能位于可视化树的深处。

稍微改变一下你的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 说明在哪里可以找到所需的处理程序。