WPF MVVM:更改 ViewModel 时不会重新加载视图

发布于 2024-10-14 01:03:45 字数 519 浏览 1 评论 0原文

我有一个基于 MVVM 模式的 WPF 应用程序。它的左侧有一棵树,右侧有一个详细信息区域。该树包含各种类型的对象,并且每种类型都有一个视图模型。在视图中,我为每种视图模型类型都有不同的数据模板(包含用户控件)。然后根据当前详细信息视图通过数据绑定选择视图。

现在,当我在树节点之间切换时,我还会为每个节点实例化一个新的详细信息视图模型,并且视图会相应更改,同时触发 DataContextChanged 事件和 Loaded 事件。也就是说,直到我开始在相同类型的对象之间切换。在这里,详细信息视图模型也会更新,但视图实例保持不变。这意味着,仅触发 DataContextChanged 事件,而不触发 Loaded 事件。

有没有办法强制触发 Loaded 事件,例如通过重新初始化视图?

我需要 Loaded 事件的原因是 WPF 在数据绑定期间触发输入控件上的选择更改事件,并且由于我具有作用于用户触发的选择更改事件的逻辑,因此我需要能够忽略由数据绑定触发的事件。目前,Loaded 事件似乎是执行此操作的最佳选择。对于所描述的问题除外。

谢谢,迈克尔

I have a WPF application based on the MVVM pattern. It has a tree on the left side and a details area on the right side. The tree contains objects of various types and I have a view model for each type. In the view, I have a different data template (containing a user control) for each view model type. The view is then selected via databinding based on the current details view.

Now, when I switch between tree nodes, I also instantiate a new details view model for each node and the view gets changed accordingly, firing both the DataContextChanged event and the Loaded event. That is, until I start to switch between objects of the same type. Here, too, the details view model gets updated, but the view instance stays the same. This means, only the DataContextChanged event is fired, but not the Loaded event.

Is there a way to force the Loaded event to fire, for instance, by re-initializing the view?

The reason why I need the Loaded event is that WPF fires the selection change events on input controls during data binding and since I have logic that acts upon user-triggered selection change events, I need to be able to ignore those triggered by data binding. For now, the Loaded event seems to be the best option to do this. Escept for the described issue.

Thanks, Michael

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

窝囊感情。 2024-10-21 01:03:45

如果需要在每次数据上下文更改时运行,请将 Loaded 处理程序中的任何逻辑移动到 DataContextChanged 处理程序。

Move whatever logic you have in the Loaded handler to the DataContextChanged handler if it needs to run every time the data context changes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文