2010-08-19 70 views
17

我正在使用Wpf Toolkit DataGrid。每当我给它分配Itemssource时,它的第一个项目被选中,并且它的selectionChanged事件被调用。我怎样才能阻止它默认选择任何行?停止Datagrid默认选择第一行

+1

你尝试了'SelectedIndex'属性设置为-1前/设置'ItemSource'后? – 2010-08-19 05:59:52

回答

30

检查您是否设置了IsSynchronizedWithCurrentItem="True"并且您需要将它设置为相似?

<DataGrid IsSynchronizedWithCurrentItem="True" ... 

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

+0

这篇文章救了我,谢谢。 – McAden 2011-08-26 23:20:24

+2

我有相反的问题 - 我想要一种方法* *使其*默认选择第一行。这个答案仍然有效。 – dlf 2016-03-09 22:09:37

10

很可能您的DataGrid绑定了像PagedCollectionView这样的具有CurrentItem属性的集合。该属性与所选行在两个方向上自动同步。解决方法是将CurrentItem设置为null。你可以这样说:

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

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

+1

+1我被这个问题困扰了很长时间,这就是解决方案。 :) – 2011-10-20 20:14:25

+0

当您需要保持CollectionViewSource和View之间的同步时,这应该是答案。 – 2017-11-04 08:36:47

0

我尝试了很多不同的东西,但什么工作对我来说是捕获第一个选择事件,并通过取消选择数据网格上的所有事件来“撤消”它。

下面是使这项工作的代码,我希望这是给别人:)有益

/* 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 */ 
     } 
    } 
} 
0

HCL的答案是正确的,但朝三暮四读者如我,这证明了混乱,我结束了在回到这里并仔细阅读之前,花更多的时间四处查看其他事情。

<DataGrid IsSynchronizedWithCurrentItem="False" ... 

是我们感兴趣的一点,而不是它的对手!

要添加我自己的价值: 财产IsSynchronizedWithCurrentItem=True意味着网格的CurrentItem将与集合的当前项目同步。设置IsSynchronizedWithCurrentItem=False就是我们想要的。

对于Xceed的Datagrid的用户(比如我是在这种情况下),那将是SynchronizeCurrent=False