1

ボタンとコンテキスト メニューが同じコマンドにバインドされています。アプリを起動すると、ボタンは有効になりますが、コンテキスト メニュー項目は有効になりません (前述したように、それらは同じコマンドにバインドされています)。ボタンをクリックした後にのみ、コンテキスト メニュー項目が有効になります。理由を知っている人はいますか?

これが動作です。

これが 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>

ありがとう!

編集:

コマンドコード:

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;
            }
        }
    }
}

コマンド イベント ハンドラー (MainWindow.xaml.cs 内):

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

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

0 に答える 0