我正在使用Wpf Toolkit 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 属性...
<DataGrid IsSynchronizedWithCurrentItem="False" ...
我们感兴趣的是这个位,而不是它的对立面!
为了添加一些价值:
IsSynchronizedWithCurrentItem=True
属性意味着网格的 CurrentItem
将与集合的当前项同步。在这里设置 IsSynchronizedWithCurrentItem=False
是我们想要的。
对于 Xceed 的 Datagrid 用户(例如我在这种情况下),应该使用 SynchronizeCurrent=False
。
我尝试了很多不同的方法,但对我有用的是捕获第一个选择事件,并通过在 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 */
}
}
}