WPF: How to enable a Command?
I don't know why the Add item in my context menu is only enabled when there is an item selected in the ListView. Does anybody knows why?
Here's my XAML code
<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>
The methods for the window are:
private void CommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
{
MessageBox.Show("ok");
}
priv开发者_运维问答ate void CommandBinding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
e.Handled = true;
}
Focus is required for the CommandBinding.CanExecute
to be called. Since selecting an item in the ListView
forces the focus to shift to the ListView
; the evaluation can occur.
If you were to place listView.Focus();
within your Window
constructor you would note that CommandBinding.CanExecute
is now called as expected and therefore enabled without an item being contained or selected within the ListView
.
Moving the binding to the Window
will still require the focus to get set within the Window
; either via an explicit call within the constructor or by another means; ex... selecting an item in the ListView
or other control within the Window
which can receive focus.
精彩评论