簡體   English   中英

WPF RoutedCommand CanExecute事件未觸發

[英]WPF RoutedCommand CanExecute event is not fired

我創建了一個內部有命令(DeleteCommand)的UserControl:

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的按鈕。 我的問題是,盡管e.CanExecute始終設置為true,但始終禁用此按鈕並且從不調用DeleteCommandCanExecute處理程序。

我試圖打電話給:

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會在哪里找到所需的處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM