停止Datagrid默认选择第一行

21
我正在使用Wpf Toolkit DataGrid。每当我将Itemssource分配给它时,它的第一项就会被选中,并且会调用其selectionChanged事件。如何阻止它默认选择任何行?

1
你尝试在设置“ItemSource”之前/之后将“SelectedIndex”属性设置为-1了吗? - Ranhiru Jude Cooray
4个回答

41

检查是否已设置IsSynchronizedWithCurrentItem="True",并且您需要它被设置为相同的值吗?

<DataGrid IsSynchronizedWithCurrentItem="True" ... 
            
            

将此属性设置为true时,选择第一个项目是默认行为。


2
我有相反的问题 - 我想要一种方法来默认选择第一行。这个答案仍然有效。 - dlf

12

很有可能你的DataGrid绑定到一个类似于PagedCollectionView的集合,该集合具有CurrentItem属性。该属性会自动在双向上与所选行同步。解决方案是将CurrentItem设置为null。你可以这样做:

PagedCollectionView pcv = new PagedCollectionView(collection);
pcv.MoveCurrentTo(null);
dataGrid.ItemsSource = pcv;

这在Silverlight中特别有用,因为它没有 DataGrid.IsSynchronizedWithCurrentItem 属性...


1
+1 我曾经陷入这个问题很长时间,但是这就是解决方案。 :) - Dan J
当您需要保持CollectionViewSource和View之间同步时,这应该是答案。 - Bassem Akl
谢谢。这对我在WinUI社区工具包数据网格中起作用。 - Umer Mehmood

7
HCL的回答是正确的,但对于像我这样快速粗略阅读的读者来说,它证明令人困惑,最终我花了更多时间去调查其他事情,然后才回到这里仔细阅读。
<DataGrid IsSynchronizedWithCurrentItem="False" ... 

我们感兴趣的是这个位,而不是它的对立面!

为了添加一些价值:

IsSynchronizedWithCurrentItem=True 属性意味着网格的 CurrentItem 将与集合的当前项同步。在这里设置 IsSynchronizedWithCurrentItem=False 是我们想要的。

对于 Xceed 的 Datagrid 用户(例如我在这种情况下),应该使用 SynchronizeCurrent=False


1

我尝试了很多不同的方法,但对我有用的是捕获第一个选择事件,并通过在 datagrid 上取消选择所有内容来“撤消”它。

以下是使其工作的代码,希望对其他人有所帮助 :)

/* Add this inside your window constructor */
this.myDataGrid.SelectionChanged += myDataGrid_SelectionChanged;

/* Add a private boolean variable for saving the suppression flag */
private bool _myDataGrid_suppressed_flag = false;

/* Add the selection changed event handler */
void myDataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    /* I check the sender type just in case */
    if (sender is System.Windows.Controls.DataGrid)
    {
         System.Windows.Controls.DataGrid _dg = (System.Windows.Controls.DataGrid)sender;

        /* If the current item is null, this is the initial selection event */
         if (_dg.CurrentItem == null)
         {
              if (!_myDataGrid_suppressed_flag)
              {
                    /* Set your suppressed flat */
                    _dgRateList_suppressed_flag = true;
                    /* Unselect all */
                    /* This will trigger another changed event where CurrentItem == null */
                    _dg.UnselectAll();

                    e.Handled = true;
                    return;
              }
         }
         else
         {
                /* This is a legitimate selection changed due to user interaction */
         }
    }
}

看起来有点不正规,但它确实救了我的命,因为我已经尝试将IsSynchronizedWithCurrentItem设置为“false”,但没有用。 - Pona

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接