How to set datagrid SelectedIndex to -1 in app.xaml

Viewed 204

So I have multiple DataGrids in a single wpf window and in the codebehind I have set the SelectedIndex property of each DataGrid to -1.

private void Window_Loaded(object sender, RoutedEventArgs e)
{
    dgPackaging.ItemsSource = vm.getPackaging();
    dgUsers.ItemsSource = vm.getUsers();
    dgFarmers.ItemsSource = vm.getAllFarmers();
    dgProducts.ItemsSource = vm.getAllProducts();
    dgPurchaseOrder.ItemsSource = vm.getAllPurchasOrders();
    dgPODescription.ItemsSource = vm.PurchaseOrderDetails;
    dgCustomers.ItemsSource = vm.getAllCustomers();

    dgFarmers.SelectedIndex = -1;
    dgUsers.SelectedIndex = -1;
    dgPackaging.SelectedIndex = -1;
    dgProducts.SelectedIndex = -1;
    dgPurchaseOrder.SelectedIndex = -1;
    dgCustomers.SelectedIndex = -1;
} 

I have a style in my app.xaml that all Datagrids use:

<Style x:Key="AdminGridStyle" TargetType="DataGrid" BasedOn="{StaticResource dataGridStyle}">
    <Setter Property="Margin" Value="3"/>
    <Setter Property="RowHeight" Value="40"/>
    <Setter Property="IsSynchronizedWithCurrentItem" Value="true"/>
    <Setter Property="Grid.ColumnSpan" Value="2"/>
    <Setter Property="Grid.RowSpan" Value="8"/>
    <Setter Property="SelectedIndex" Value="-1"/>
</Style>

I am able to set the SelectedIndex property value to any number greater than or equal to zero. When I set the property value to -1, the first row of the Datagrids are selected. So my question is , is it possible to set the SelectedIndex property to -1 in the AdminGridStyle, and if so, how?

1 Answers

You don't need to set the SelectedIndex property at all if you don't want to select any item in the DataGrid(s).

Just remove the IsSynchronizedWithCurrentItem setter from your Style:

<Style x:Key="AdminGridStyle" TargetType="DataGrid" BasedOn="{StaticResource dataGridStyle}">
    <Setter Property="Margin" Value="3"/>
    <Setter Property="RowHeight" Value="40"/>
    <Setter Property="Grid.ColumnSpan" Value="2"/>
    <Setter Property="Grid.RowSpan" Value="8"/>
    <Setter Property="SelectedIndex" Value="-1"/>
</Style>
Related