2010-08-19 158 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