WPF-MVVM:从 ViewModel 设置 UI 控制焦点
在 MVVM 架构中设置控制焦点的良好实践是什么?
我设想的方式是使用 ViewModel 上的一个属性,在需要时触发焦点更改。然后让 UI 控件绑定/侦听该属性,以便在它发生更改时设置适当的焦点。
我将其视为 ViewModel 的事情,因为我想在 ViewModel 执行某个操作(例如加载某些数据)后适当地设置焦点。
最佳做法是什么?
What is a good practice of setting control focus in MVVM architecture.
The way I envision it, is with a property on the ViewModel that would trigger a focus change when needed. And than have the UI controls bind/listen to that property so that if it changes, appropriate focus will be set.
I see it as a ViewModel thing, because i want to set focus appropriate after a certain action was performed by the ViewModel, such as loading certain data.
What's the best practice?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
按照此处答案中的建议使用 IsFocused 附加属性:从视图模型 (C#) 将焦点设置在 WPF 中的文本框上
然后您可以简单地绑定到视图模型中的属性。
Use the IsFocused Attached Property as suggested in the Answer here: Set focus on textbox in WPF from view model (C#)
Then you can simply bind to a property in your viewmodel.
如果您使用的是 Caliburn.Micro,这里是我创建的一项服务,用于将焦点设置为从 Screen 继承的视图中的任何 Control。
如何使用这个?
从继承自 Caliburn.Micro.Screen 或 Caliburn.Micro.ViewAware 的 ViewModel
this.SetFocus(()=>ViewModelProperty);
或者
this.SetFocus("Property");
它是如何工作的?
此方法将尝试在可视化视图树中搜索元素,并将焦点设置到任何匹配的控件。如果没有找到这样的控件,那么它将利用 Caliburn.Micro 使用的 BindingConventions。
例如,
它将在控件的 BindingExpression 中查找属性。
对于 TextBox,它将查看该属性是否绑定到 Text 属性,然后设置焦点。
If you are using Caliburn.Micro, here is a service that I created to set Focus to any Control in the view inherited from Screen.
How to use this?
From your ViewModel inherited from Caliburn.Micro.Screen or Caliburn.Micro.ViewAware
this.SetFocus(()=>ViewModelProperty);
or
this.SetFocus("Property");
How it works?
This method will try to search for an element in the Visual Tree of View and focus will be set to any matching control. If no such control found, then it will make use of the BindingConventions used by Caliburn.Micro.
For ex.,
It will look for the Propery in the BindingExpression of the control.
For TextBox, it will look whether this property is binded to Text property then the focus will be set.
ViewModel 向 View 抛出一个事件,告诉它操作已完成,并且 View 将设置焦点。
The ViewModel throws an event to the View telling it that the action has been completed, and the View will set the focus.