绑定“WindowState”使用 MVVM 的 WPF 中窗口的属性
我将主窗口的“WindowState”属性绑定到 ViewModel,以便通过命令更改窗口的状态,但第一次最小化窗口时,它会像 Excel 文件中的工作表一样最小化。是否有解决此问题的方法或将“WindowState”属性绑定到我的 ViewModel 以便窗口正确最小化的正确方法?
I bound the "WindowState" property of my main window to my ViewModel in order to change the state of the window by a command, but the first time I minimize the window it minimizes like a worksheet does in an Excel file. Is there a work around for this or a correct way to bind the "WindowState" property to my ViewModel so that the window minimizes correctly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
这是一个使用中继命令逻辑进行测试的示例解决方案。您将获得有关采用模型-视图-视图模型设计模式的 WPF 应用程序的更多详细信息。
并在 Windows ViewModel 中
this is a sample work around that tested with Relaying Command Logic. You will get more detail on WPF Apps With The Model-View-ViewModel Design Pattern .
and in the Windows ViewModel
我认为您不应该关心视图模型中的窗口状态,这是完全错误的,因为较低级别的层知道较高级别的层(因此错误的关注点分离(SOC))。
在这种情况下,我通常做的是从包含视图模型的控件或窗口(即视图)的代码隐藏中订阅视图模型中的更改。在这种情况下,在代码隐藏中编写代码是有效的,因为它仅在视图中使用(因此代码隐藏是此逻辑的完美位置,您确实不想对其进行单元测试)。
I don't think you should care about the window state in a view model, it's completely wrong because a lower-level layer is aware of a higher-level layer (thus wrong Separation of Concerns (SOC)).
What I normally do in this case is subscribe to changes in the view model from the code-behind of the control or window (thus the view) containing the view model. In this case, it is valid to write code in the code-behind because it is only used in the view (and thus the code-behind is the perfect location for this logic, which you really don't want to unit test).
另一个需要考虑的选项是通过命令和事件来订阅后台代码,例如:
本例中的命令会影响虚拟机。 Click 事件仅改变窗口状态。
Another option to consider is subscribing both via a command AND an event to code behind, e.g:
The command in this case affects the VM. The Click event, only changes the Window state.
我已经找到了自己的解决方案,它非常适合 MVVM。我使用行为来查找用户控件的父窗口并跟踪 WindowState 更改。
此行为可以在任何 UserControl 中使用,就像在 ViewModel 中绑定 WindowState 一样。
I have found my own solution which is perfectly suited to MVVM. I'm using behavior to find the parent window of the user control and track WindowState changes.
This behavior can be used in any UserControl like this with bound WindowState in ViewModel.