繁体   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