Race
Race

Reputation: 424

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>

Upvotes: 2

Views: 4553

Answers (2)

alpinsky
alpinsky

Reputation: 524

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

Upvotes: 8

Shaharyar
Shaharyar

Reputation: 12459

Use event LostFocus to identify when you lose focus of the DataGrid, and cancel selection of selected rows in that event.

For cancel selection:

yourDataGrid.UnselectAll()

Upvotes: 0

Related Questions