WPF数据表格:如何通过编程方式清除选择?

12

如何清除选择内容?

UnselectAllUnselectAllCells方法,但它们无法起作用。另外,设置SelectedItem = nullSelectedIndex = -1也不起作用。

此外,我不想完全禁用选择功能,我只想清除当前的选择(如果有),然后以编程方式设置新的选择。

5个回答

26
dataGrid.UnselectAll()

对于行模式


5

要清除当前选择,您可以使用以下代码(如您所见,它在单选和扩展模式下是不同的)

if(this.dataGrid1.SelectionUnit != DataGridSelectionUnit.FullRow)
    this.dataGrid1.SelectedCells.Clear();

if (this.dataGrid1.SelectionMode != DataGridSelectionMode.Single) //if the Extended mode
    this.dataGrid1.SelectedItems.Clear();
else 
    this.dataGrid1.SelectedItem = null;

要通过编程方式选择新项,请使用以下代码:

if (this.dataGrid1.SelectionMode != DataGridSelectionMode.Single) 
{    //for example, select first and third items
    var firstItem = this.dataGrid1.ItemsSource.OfType<object>().FirstOrDefault();
    var thirdItem = this.dataGrid1.ItemsSource.OfType<object>().Skip(2).FirstOrDefault();

    if(firstItem != null)
        this.dataGrid1.SelectedItems.Add(firstItem);
    if (thirdItem != null)
        this.dataGrid1.SelectedItems.Add(thirdItem);
}
else
    this.dataGrid1.SelectedItem = this.dataGrid1.ItemsSource.OfType<object>().FirstOrDefault(); //the first item

@miliu 是的,我的之前的代码不正确。我已经修正了答案。 - vortexwolf
对于我的情况,我找到了一个解决方法:当我调用“Dispatcher.BeginInvoke(DispatcherPriority.Background,new Action(()=> grid.Items.Refresh()))”刷新数据上下文时,选择项会消失。 - newman
在Silverlight Datagrid中,如果您不使用扩展选择模式(多选),似乎无法执行grid.SelectedItems.Clear(),而必须执行grid.SelectedItem=null。也许在WPF中也是类似的情况? - George Birbilis
1
@GeorgeBirbilis 我的回答早已过去,我不记得了。但是我的代码有if-else组合,根据选择模式使用SelectedItems.ClearSelectedItem = null。如果出现新的SelectionMode值,我认为这个if-else应该被重写。 - vortexwolf
是的,看起来他们使用了相同奇怪的模式。 - George Birbilis
显示剩余3条评论

2
DataGrid.UnselectAllCells()

对我来说它有效。


1

禁用和重新启用DataGrid对我有用。


0
你是想清除选定的行/单元格吗? 我的理解是你想要清除整个DataGrid。 如果是这样,你可以这样做:
myDataGrid.ItemsSource = null;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接