gpt4 book ai didi

wpf - 在 View 中访问 ViewModel 数据

转载 作者:行者123 更新时间:2023-12-03 10:35:46 26 4
gpt4 key购买 nike

我只是想问一下是否可以访问ViewModel's View 中的数据后端?

基本上我只需要检查一下 ViewModel's属性已设置(当用户选择某些内容时设置),如果不是,我将用户重定向到另一个 View告诉他他需要先选择一些东西。这是一个糟糕的设计实践还是可以,只是为了像这样的小检查?真的不想实现一个静态类并将数据外推到它,而是检查它。

与此密切相关的另一个问题是,我可以调用 View 中的方法吗? (当 View 关闭时),取消注册该特定的 ViewModel来自 IoC 容器(此 ViewModel 不是单例)。另一种方法是从 View 向 ViewModel 发送消息。当View正在关闭,当 ViewModel得到它自己注销的消息。我试图解决的问题是,每次 ViewModel请求它必须是一个新的,但我的 IoC 容器缓存了它们,使我的程序成为内存占用。所有ViewModels在应用程序退出时释放,表示 x ViewModels即使很可能不需要它们,它们仍将存在于缓存中。

最佳答案

Basically I just need a check to see if a ViewModel's property is set (which gets set when the user selects something), and if it's not I'll just redirect the user to another View telling him he needs to select something first. Is this a poor-design practice or is it OK, just for a minor check like this?


检查一些 ViewModel的值似乎没有错属性并反射(reflect) View 上的更改边。 View状态可以“绑定(bind)”到 ViewModel WPF 数据绑定(bind)机制的状态: Binding , Triggers ( Trigger , DataTrigger , EventTrigger ), Commands (包括 EventToCommand )等。
但有时处理 ViewModel 很有用 ViewModel 的状态变化本身使用 UI 服务。例如, IWindowService可以引入接口(interface)以允许从 ViewModel 的上下文中打开窗口执行。

Another question tightly related to this, is can I call a method from the View (when the View is closing), that unregisters that particular ViewModel from the IoC container (this ViewModel isn't singleton).

...

The problem I'm trying to solve with this is that, every time that ViewModel is requested it has to be a new one, but my IoC container caches them, making my program a memory hog. All of the ViewModels get released on application exit, meaning x ViewModels will still exist in the cache even though they're most likely not needed.


当注册被指定为“resolve per call behavior”(而不是“singleton behavior”)时,所描述的依赖容器“缓存效应”似乎很奇怪。请检查注册是否被指定为“resolve per call behavior”(例如, PerResolveLifetimeManagerUnity Container Lifetime Managers)。
更新 ViewModel因为使用了 SimpleIoC 容器,所以存在生命周期问题。
我想推荐使用另一个依赖注入(inject)容器(具有适当的生命周期管理)来使实现不那么复杂和容易出错。
但是,如果有 强烈需求使用 SimpleIoC 容器,某种 ViewModel生命周期管理可以通过以下方式实现:
  • SimpleIoc.Default.GetInstance<ViewModel>(key);用于解析 ViewModel 实例的方法调用;
  • SimpleIoc.Default.Unregister(key);在不再需要实例时取消注册(Closed 事件等)。

  • 可以在这里找到实现: answer #1 , answer #2 .

    关于wpf - 在 View 中访问 ViewModel 数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30060548/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com