I am trying to make a simple TODO App with WPF using MVVM. I have the tasks in Datagrid and a right click context menu with Delete option. I don't want the context menu to show when there are no elements in Data Grid. What can I do to solve it?
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<DataGrid ItemsSource="{Binding Path=TaskList}" SelectedItem="{Binding SelectedTask}" AutoGenerateColumns="False">
<DataGrid.ContextMenu >
<ContextMenu>
<MenuItem Header="Delete" Command="{Binding OpenDialogCommand}" CommandParameter="{Binding PlacementTarget.SelectedItem, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ContextMenu}}}"></MenuItem>
</ContextMenu>
</DataGrid.ContextMenu>
<DataGrid.Columns>
<DataGridTextColumn Header="Priority" Width="auto" Binding="{Binding Path=Id}"/>
<DataGridTextColumn Header="Task" Width="auto" Binding="{Binding Path=TaskName}"/>
</DataGrid.Columns>
</DataGrid>
I got a simple hack to solve this. I changed the row definition from * to auto for row 2; This will stop context menu from showing when you click anywhere other than Datagrid Elements.
<RowDefinition Height="auto"/>
Also to remove one extra row which always shows(and display context menu when right clicked)
This worked.
<DataGrid Margin ="10" x:Name="dgTaks" Grid.Row="1" Grid.ColumnSpan="2" ItemsSource="{Binding Path=TaskList}" SelectedItem="{Binding SelectedTask}" AutoGenerateColumns="False" **CanUserAddRows="False"**>