Search code examples
c#wpfwpfdatagrid

WPF howto click out of rows in DataGrid to unselect item


How can I remove selection of Row if I click outside of rows. Like in the red area of the image showing below

enter image description here

The related xaml shows below:

<Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*" />
            <RowDefinition Height="auto" />
        </Grid.RowDefinitions>

        <DataGrid x:Name="ClientsList" Grid.Row="0" Grid.Column="0" CanUserAddRows="False"
                  SelectionMode="Extended" SelectionUnit="FullRow"
                  ItemsSource="{Binding ClientItems}" LostFocus="ClientsList_LostFocus" Background="Green">
        </DataGrid>

        <StackPanel Margin="2" Grid.Row="1" Grid.Column="0" Orientation="Horizontal">
            <Button x:Name="AddButton"  Margin="2,0,0,0" Content="+" Height="25" Width="40" Click="AddButton_Click"/>
            <Button x:Name="DeleteButton" Margin="2,0,0,0" Content="-" Height="25" Width="40" Click="DeleteButton_Click"/>
        </StackPanel>
    </Grid>

Solution

  • In you case if empty area was clicked then OriginalSource is gonna be ScrollViewer (if no additional styling applied). Try to add the following MouseUp event handler to DataGrid:

        private void OnDataGridMouseUp(object o, MouseButtonEventArgs e)
        {
            if (e.OriginalSource is ScrollViewer)
            {
                ((DataGrid) o).UnselectAll();
            }
        }