【问题标题】:How to set datagrid SelectedIndex to -1 in app.xaml如何在 app.xaml 中将 datagrid SelectedIndex 设置为 -1
【发布时间】:2018-03-17 23:34:11
【问题描述】:

所以我在单个 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 中有一个所有 Datagrids 都使用的样式:

<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 时,选择了 Datagrids 的第一行。 所以我的问题是,是否可以在 AdminGridStyle 中将 SelectedIndex 属性设置为 -1,如果可以,如何设置?

【问题讨论】:

  • 如果您不想选择任何项目,为什么不设置 SelectedIndex 属性?
  • @mm8 如果我从代码隐藏和 App.xaml 中删除 SelectedIndex 并运行程序,每个数据网格的第一行仍然被选中
  • 如果删除 IsSynchronizedWithCurrentItem 设置器会怎样?
  • @mm8 成功了,谢谢! :)

标签: c# wpf xaml datagrid app.xaml


【解决方案1】:

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

只需从您的 Style 中删除 IsSynchronizedWithCurrentItem 设置器:

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

【讨论】:

    猜你喜欢
    • 2014-06-05
    • 2014-04-17
    • 2012-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-10
    相关资源
    最近更新 更多