很难说出这里问的是什么。这个问题是模棱两可的、模糊的、不完整的、过于宽泛的或修辞的,无法以目前的形式得到合理的回答。如需帮助澄清这个问题以便重新打开它,visit the help center .
9年前关闭。
我有一个简单的 ViewModel
public class TestViewModel : ViewModelBase, IDisposable
{
public TestViewModel()
{
Messenger.Default.Register<string>(this, MessageHandling);
}
public void MessageHandling(string message)
{
System.Windows.MessageBox.Show(message);
}
public override void Cleanup()
{
Messenger.Default.Unregister(this);
base.Cleanup();
}
}
我像这样在我的 XAML 中使用它:
<Window.Resources>
<ResourceDictionary>
<vm:TestViewModel x:Key="ViewModel"></vm:TestViewModel>
</ResourceDictionary>
</Window.Resources>
<Grid DataContext="{Binding Source={StaticResource ViewModel}}">
</Grid>
任何人都可以帮助我们处理这个 ViewModel,通过处理我的意思是我应该订阅哪个事件来调用 VM 方法清理?因为如果我不进行清理,ViewModel 将保留在内存中并仍然处理消息。
我希望我解释得当:)
提前致谢
最佳答案
首先,它取决于您何时要处理它。你没有说清楚。我首先以为您的意思是“当应用程序关闭时”,然后我会使用 exit事件。但我被你的说法激怒了
Because if I don't do Cleanup the ViewModel remains in memory and still handles messages. I hope i explained it properly
只有当您想要处理但您的应用程序仍需要运行时才会发生这种情况。如果您的应用程序关闭,则内存中没有任何内容,也不再处理任何消息。但不依赖它仍然是一个好习惯。
因此,如果您的意思是“当应用程序关闭时”,这就是您的答案。
关于wpf - 处理静态资源 ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11807782/