停止Datagrid默认选择第一行

问题描述 投票:19回答:4

我正在使用Wpf Toolkit DataGrid。每当我为其分配Itemssource时,它的第一个项目被选中并且其selectionChanged事件被调用。如何在默认情况下阻止它选择任何行?

c# wpf datagrid
4个回答
38
投票

检查您是否设置了IsSynchronizedWithCurrentItem="True",并且要求它设置相似吗?

<DataGrid IsSynchronizedWithCurrentItem="True" ... 

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


11
投票

有可能您的DataGrid绑定到具有CurrentItem属性的PagedCollectionView之类的集合。此属性在两个方向上与所选行自动同步。解决方案是将CurrentItem设置为null。你可以这样做:

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

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


2
投票

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 */
         }
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.