不会触发WPF RoutedCommand CanExecute事件

时间:2015-03-24 20:32:28

标签: c# wpf xaml command

我创建了一个UserControl,里面有一个命令(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的Button。我的问题是这个按钮总是被禁用,并且永远不会调用DeleteCommandCanExecute处理程序,尽管e.CanExecute总是设置为true。

我试过打电话:

CommandManager.InvalidateRequerySuggested();

但没有任何反应。该事件从未被解雇。也许我正在做错的CommandBinding。

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

1 个答案:

答案 0 :(得分:0)

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