2011-02-28 56 views
2

我不知道为什么我的上下文菜单中的添加项目只有在ListView中选择了一个项目时才启用。有人知道为什么吗?WPF:如何启用命令?

这里是我的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

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

回答

5

焦点时调用。由于选择ListView中的项目会迫使焦点转移到ListView;评估可能发生。

如果你放置你的listView.Focus();构造Window内,你会注意到,如预期CommandBinding.CanExecute现在被称为与被包含或ListView内选择没有项目,因此启用。

将绑定移动到Window仍然需要重点设置在Window;要么通过构造函数中的显式调用,要么通过其他方式; ex ...选择ListView中的项目或Window中可以获得焦点的其他控件。