c# - 如何在 app.xaml 中将 datagrid SelectedIndex 设置为 -1

标签 c# wpf xaml datagrid app.xaml

所以我在单个 wpf 窗口中有多个 DataGrid,在代码隐藏中我将每个 DataGrid 的 SelectedIndex 属性设置为 -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;
} 

我的 app.xaml 中有一个所有数据网格都使用的样式:

<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>

我可以将 SelectedIndex 属性值设置为大于或等于零的任何数字。 当我将属性值设置为 -1 时,Datagrid 的第一行被选中。 所以我的问题是,是否可以在 AdminGridStyle 中将 SelectedIndex 属性设置为 -1,如果可以,如何设置?

最佳答案

如果您不想选择 DataGrid(s) 中的任何项目,则根本不需要设置 SelectedIndex 属性。

只需从您的 Style 中删除 IsSynchronizedWithCurrentItem setter:

<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>

关于c# - 如何在 app.xaml 中将 datagrid SelectedIndex 设置为 -1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46601028/

相关文章:

c# - 如何限制物体旋转到一定程度?

wpf - 如何仅使用 XAML 而不使用隐藏代码对 ListBox 进行排序?

c# - 如何删除 RichTextBox 中自动生成的第一行

c# - 如何在域服务上调用调用操作?

c# - 如何使用 FluentMigrator 在预览 sql 脚本中添加开始事务和回滚事务?

c# - 无法获取 DataTable 进行排序

c# - 如何用C#写一个文本文件

wpf - XAML 命名空间 : winfx vs netfx

wpf - 元素主机 : Images in XAML Ribbon Causing Issues

c# - 为应用程序中的所有文本框选择 TextBox 中的所有文本