确定 WPF 窗口中谁拥有焦点
我们正在使用 WPF 并有一个从 DockingLibrary 派生的窗口。该窗口有一个网格,其中包含多个项目,其中一个是 WPF 数据网格。我们正在使用 MV-VM 模式。创建并显示此窗口时,不会选择此数据网格中的任何行。我们可以通过执行以下操作将行设置为突出显示:
SharedWindow.ShipmentWin.shipmentDataGrid.SelectedIndex = 0;
这会导致数据网格中的第一行显示为突出显示。但是,并非总是存在其中之一,这一行未被选中,也没有焦点。我尝试在该行上设置 IsSelected 和 Focus,如下所示:
SharedWindow.ShipmentWin.ShipVM.IsSelected = true;
bool focused = SharedWindow.ShipmentWin.shipmentDataGrid.Focus();
我的处理方式是否全部错误,是否有其他方法可以选择数据网格中的第一行并将焦点设置为其?通常,当创建数据网格时,直到用户鼠标单击所需的行为止,不会选择任何行。
任何想法将不胜感激。
谢谢!
We are using WPF and have a window derived from a DockingLibrary. This window has a grid with multiple items in it, one being a WPF datagrid. We are using the M-V-VM pattern. When this windown is created and shown, none of the rows in this datagrid are selected. We can set the row to display as highlighted by doing something like:
SharedWindow.ShipmentWin.shipmentDataGrid.SelectedIndex = 0;
This causes the first row in the datagrid to be shown as highlighted. But, and isn't there always one of these, this row is not Selected nor does it have Focus. I tried setting IsSelected and Focus on this row as in:
SharedWindow.ShipmentWin.ShipVM.IsSelected = true;
bool focused = SharedWindow.ShipmentWin.shipmentDataGrid.Focus();
Am I going about this all wrong and is there some other way to Select the first row in the datagrid and set focus to it? Typically, when a datagrid is created, no row is selected until the user mouse clicks on the desired row.
Any thoughts would be greatly appreciated.
thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
查看 FocusManager 。它允许您通过 SetFocusedElement 方法将焦点设置到另一个 UI 元素。此外,它还允许您确定应用程序中当前聚焦的元素,这可以方便地调试焦点问题。 Snoop 也很有用。它在底部状态栏中显示当前聚焦的元素。
如果您使用 WPF 工具包中的 DataGrid,请准备好发现一些与焦点处理相关的错误。有些问题最近已得到解决。
Have a look at the FocusManager. It allows you the set the focus to another UI element via the SetFocusedElement method. Additionally, it allows you to determine the currently focused element in your application which is can get handy to debug focus issues. Snoop can be useful, too. It shows the currently focused element in the bottom status bar.
If you use the DataGrid from the WPF Toolkit, be prepared to find some bugs in relation to focus handling. Some have been addressed recently.
还值得了解逻辑焦点和键盘焦点之间的区别,它们是完全不同的动物。
.Focus()
方法有时仅设置逻辑焦点 - 这可能不是您想要的。Focus 的文档
方法告诉您,如果设置了键盘焦点,它将返回true
,否则返回false
。It's also worth understanding the difference between logical focus and keyboard focus, which are quite different animals. The
.Focus()
method sometimes only sets logical focus - which probably isn't what you want.The documentation for the
Focus
method tells you that it will returntrue
if the keyboard focus was set, andfalse
otherwise.