Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/307.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# WPF:如何启用命令?_C#_Wpf - Fatal编程技术网

C# WPF:如何启用命令?

C# WPF:如何启用命令?,c#,wpf,C#,Wpf,我不知道为什么只有在ListView中选择了一个项目时,才会启用我上下文菜单中的添加项目。有人知道为什么吗 这是我的XAML代码 <Window x:Class="Vokabular1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

我不知道为什么只有在ListView中选择了一个项目时,才会启用我上下文菜单中的添加项目。有人知道为什么吗

这是我的XAML代码

    <Window x:Class="Vokabular1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid HorizontalAlignment="Stretch" Name="grid" VerticalAlignment="Stretch">
            <Grid.ColumnDefinitions>
                <ColumnDefinition />
                <ColumnDefinition />
            </Grid.ColumnDefinitions>

            <ListView Grid.Column="0" HorizontalAlignment="Stretch" Margin="10,10,10,10" Name="listView" VerticalAlignment="Stretch">
                <ListView.View>
                    <GridView />
                </ListView.View>
                <ListView.CommandBindings>
                    <CommandBinding Command="New" 
                        Executed="CommandBinding_Executed" 
                        CanExecute="CommandBinding_CanExecute" />
                </ListView.CommandBindings>
                <ListView.ContextMenu>
                    <ContextMenu>
                        <MenuItem Name="Add" Header="_Add"    Command="New" />
                        <MenuItem Header="Delete" Command="Delete" IsEnabled="True" />
                    </ContextMenu>
                </ListView.ContextMenu>
                <ListViewItem />  
            </ListView>            
        </Grid>
    </Grid>
</Window>

调用
CommandBinding.CanExecute
需要焦点。因为在
列表视图
中选择一个项目会迫使焦点转移到
列表视图
;可以进行评估

如果要放置
listView.Focus()
窗口中
构造函数中,您会注意到
CommandBinding.CanExecute
现在按预期被调用,因此在
列表视图中没有包含或选择项的情况下被启用

将绑定移动到
窗口
仍需要在
窗口
内设置焦点;通过构造函数内的显式调用或通过其他方式;前任。。。在
列表视图
中选择一个项目,或在
窗口
中选择可以接收焦点的其他控件

private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
    MessageBox.Show("ok");
}

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