如何在mvvm wpf模型中关闭relay命令

发布于 2024-11-19 23:10:17 字数 336 浏览 3 评论 0原文

我有这个应用程序使用 MVVM wpf 模型以及 John Smith 的中继命令类。它有两个主要问题:

  1. 即使在处理视图模型并将命令设置为空之后,它们仍然会被触发。

  2. 视图模型虽然已被处理掉,但似乎仍然在内存中。它在顶部使用选项卡控件,即使关闭选项卡后内存也永远不会被清理。这与视图模型有关,因为一旦视图模型的属性设置为 null,下次打开不同的选项卡时,视图模型将尝试访问已处理掉的属性。仅供参考,这里不涉及单例。

它使用中继命令类,问题最终在于即使目标对象没有引发命令,命令也会被触发,即命令链接到的按钮没有被单击,但在关闭其子窗口时仍然会触发它。

I have this app using MVVM wpf model along with John Smith's relay command class. There are two main issues with it:

  1. Even after disposing the view model and setting the commands to null, they are still fired afterwards.

  2. The view model although disposed off, still seems to be in memory. It's using tab control on top and the memory never gets cleaned even after closing the tabs. This is related to the view model since once the properties of the view model are set to null, the next time you open a different tab the view model tries to access the property that was disposed off. FYI there are no singletons involved here.

It is using the relay command class and the problem eventually lies here where the commands are being fired even though the target object has not raised it i.e. the button a command is linked to is not clicked but still it fires it when closing its child window.

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

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

发布评论

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

评论(1

谢绝鈎搭 2024-11-26 23:10:18

将命令属性设置为 null 后,引发命令属性的 PropertyChanged 事件。

public class ViewModel : INotifyPropertyChanged, IDisposable
{
   public event PropertyChangedEventHandler PropertyChanged;
   public void Dispose()
   {
      Command = null;
   }

   public RelayCommand Command
   {
      get{return m_command;}
      set
      {
         if(m_command == value)
            return;
         m_command = value;
         if (PropertyChanged != null)
            PropertyChanged (this, new PropertyChangedEventArgs ("Command");
      }
   }
}

Raise the PropertyChanged event for the command properties after you set them to null.

public class ViewModel : INotifyPropertyChanged, IDisposable
{
   public event PropertyChangedEventHandler PropertyChanged;
   public void Dispose()
   {
      Command = null;
   }

   public RelayCommand Command
   {
      get{return m_command;}
      set
      {
         if(m_command == value)
            return;
         m_command = value;
         if (PropertyChanged != null)
            PropertyChanged (this, new PropertyChangedEventArgs ("Command");
      }
   }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文