2011-02-28 58 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中可以獲得焦點的其他控件。