簡體   English   中英

停止 Datagrid 默認選擇第一行

[英]Stop Datagrid selecting first row by default

我正在使用 Wpf 工具包 DataGrid。 每當我將 Itemssource 分配給它時,它的第一個項目就會被選中並調用它的 selectionChanged 事件。 默認情況下,如何阻止它選擇任何行?

檢查您是否已設置IsSynchronizedWithCurrentItem="True"並且您需要將其設置為相同?

<DataGrid IsSynchronizedWithCurrentItem="True" ... 
            
            

將此屬性設置為 true,第一項的選擇是默認行為。

很有可能您的 DataGrid 綁定到一個像 PagedCollectionView 這樣的具有 CurrentItem 屬性的集合。 此屬性與所選行在兩個方向上自動同步。 解決方案是將 CurrentItem 設置為 null。 你可以這樣做:

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

這在 Silverlight 中特別有用,它沒有DataGrid.IsSynchronizedWithCurrentItem屬性...

HCL 的回答是正確的,但對於像我這樣快速而松散的讀者來說,事實證明它令人困惑,我最終花了更多時間四處調查其他事情,然后再回到這里仔細閱讀。

<DataGrid IsSynchronizedWithCurrentItem="False" ... 

是我們感興趣的那一點,而不是它的對手!

添加我自己的一些值:屬性IsSynchronizedWithCurrentItem=True表示網格的CurrentItem將與集合的當前項目同步。 在這里設置IsSynchronizedWithCurrentItem=False是我們想要的。

對於 Xceed 的 Datagrid 用戶(例如我在這種情況下),這將是SynchronizeCurrent=False

我嘗試了許多不同的事情,但對我有用的是捕獲第一個選擇事件並通過取消選擇數據網格上的所有事件來“撤消”它。

這是使這項工作的代碼,我希望它對其他人有益:)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM