WPF DataGrid在行删除后丢失了焦点 [英] WPF DataGrid lost focus after row delete

查看:308
本文介绍了WPF DataGrid在行删除后丢失了焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用WPF DataGrid行删除键盘上的删除按键。
但是,行删除后,DataGrid失去了焦点,DataGrid.SelectedIndex = -1。

I am using WPF DataGrid row deletion by keyboard "Delete" key press. However, after the row is deleted, DataGrid lost its focus, and DataGrid.SelectedIndex = -1.

与WinForm datagrid相比,行被删除后,焦点自动转移到下一个可聚焦行,这是更合理的。

Compared to WinForm datagrid, after a row is deleted, the focus automatically shift to the next focusable row, which is much more reasonable.

通过下一个焦点,我的意思是,例如:

By "next focusable", I mean, e.g.:

Row A
Row B
Row C

If we delete Row A, the next focusable will be Row B.
If we delete Row B, the next focusable will be Row C.
If we delete Row C, the next focusable will be Row B (the last row).

如何在WPF datagrid中实现相同的效果?

顺便说一句,以下是一个例子,它关注删除后的第一行,这不是理想的,因为我们希望它成为下一个可调整的行。 p>

By the way, the following is an example that focuses on the first row after deletion, which is not ideal, since we wanted it to be the "next focusable row".

    private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (e.RemovedItems.Count > 0)
        {
            DataGrid grid = sender as DataGrid;
            if (grid.SelectedIndex == -1)
            {
                grid.SelectedCells.Clear();
                grid.SelectedIndex = 0;
            }
        }
    }

任何想法?

谢谢。

推荐答案

您将DataGrid绑定到什么?您是否尝试过CollectionView( MSDN )?这有道具像CurrentPosition和MoveCurrentToNext()方法。您可以获取正在删除的行的当前位置,然后根据CollectionView的排序顺序找到下一个。

What are you binding your DataGrid to? Have you tried a CollectionView (MSDN)? That has props like CurrentPosition and the MoveCurrentToNext() method. You could get the current position of the row being deleted and then locate the next one based on the sort order of the CollectionView.

更新:
如果您正在进行MVVM,请禁用DataGrid的删除(查看此答案),并将您的VM删除收藏品。你会知道要删除哪个项目,所以你应该能够弄清楚下一个(或之前)项目是什么。让您的VM公开一个SelectedItem属性,您将绑定到DataGrid.SelectedItem。在您的虚拟机上设置SelectedItem,并且应该在DataGrid中选择该行。

Update: If you're doing MVVM, disable the DataGrid's delete (see this answer) and have your VM remove the item from the collection. You'll know which item is being removed so you should then be able to figure out what the next (or prior) item is. Have your VM expose a SelectedItem property which you'll bind to the DataGrid.SelectedItem. Set the SelectedItem on your VM and the row should be selected in the DataGrid.

这听起来像WinForms Datagrid处理了很多这样的开箱即可,所以你可能会感觉到像你正在重塑轮廓,这对于在旧UX技术中自动工作的东西来说,这是很多工作。

It sounds like the WinForms Datagrid handled a lot of this out of the box so you probably feel like you're reinventing the wheel and that this is a lot of work for something that just worked automatically in the "old" UX technology.

这篇关于WPF DataGrid在行删除后丢失了焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆