开发者

WPF ContextMenu CommandBinding disabled

开发者 https://www.devze.com 2023-04-12 09:48 出处:网络
I have a button and a context menu bound t开发者_如何学编程o the same Command, when I start the app, the button is enabled, but the context menu item isn\'t (as I said, they\'re bound to the same comm

I have a button and a context menu bound t开发者_如何学编程o the same Command, when I start the app, the button is enabled, but the context menu item isn't (as I said, they're bound to the same command). The context menu item becomes enabled only after I click the button. Does anybody know why?

This is the behavior.

And this is the XAML:

<Window.CommandBindings>
    <CommandBinding Command="local:LocalCommandManager.ShowDialogCommand" CanExecute="CanExecuteShowDialogCommand" Executed="ShowDialogCommandExecuted" />
    <CommandBinding Command="local:LocalCommandManager.DontShowDialogCommand" CanExecute="CanExecuteDontShowDialogCommand" Executed="DontShowDialogCommandExecuted" />
</Window.CommandBindings>
<Window.ContextMenu>
    <ContextMenu>
        <MenuItem Command="local:LocalCommandManager.ShowDialogCommand" />
        <MenuItem Command="local:LocalCommandManager.DontShowDialogCommand" />
    </ContextMenu>
</Window.ContextMenu>
<Grid Background="Red">
    <Button Command="local:LocalCommandManager.ShowDialogCommand" Content="Show Dialog" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="6" />
</Grid>

Thanks!

EDIT:

Command code:

public static class LocalCommandManager
{
    private static object syncRoot = new object();

    private static RoutedUICommand _showDialogCommand;
    public static RoutedUICommand ShowDialogCommand
    {
        get
        {
            lock (syncRoot)
            {
                if (_showDialogCommand == null)
                    _showDialogCommand = new RoutedUICommand("Show Dialog", "ShowDialogCommand", typeof(LocalCommandManager));
                return _showDialogCommand;
            }
        }
    }
}

Command event handlers (in MainWindow.xaml.cs):

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

private void ShowDialogCommandExecuted(object sender, ExecutedRoutedEventArgs e)
{
    MessageBox.Show("Dialog");
}
0

精彩评论

暂无评论...
验证码 换一张
取 消