创建新的ViewModel实例时,视图状态保持不变 [英] View state remains the same when a new ViewModel instance is created MVVM

查看:61
本文介绍了创建新的ViewModel实例时,视图状态保持不变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我敢肯定,答案似乎已经存在,只是似乎找不到.我有一个SubView,它在MainViewModel中动态运行.然后使用样式将其显示给用户.当我创建SubViewModel的新实例时,如果视图的类型与以前相同,则不会重新创建该视图.这是一个问题,因为所选选项卡保持不变,并且没有重置为第一个选项卡.尽管我可以将选定的选项卡索引保存在ViewModel中以进行重置,但我认为它纯粹是View状态,不应存在于ViewModel中.我假设这是样式,没有注意到实例已更改.无论如何,每次ViewModel更改时都强制View创建一个新实例吗?

I'm sure the answer to this is already out there just can't seem to find it. I have a SubView which I am dynamically in the the MainViewModel. This is then displayed to the user using a style. When I create a new instance of the SubViewModel the View is not recreated if it of the same type as it was before. This is an issue as the selected tab remains the same and is not reset to the first tab. Although I could just save the selected tab index in the ViewModel to reset it I feel it is purely View state and should not exist in the ViewModel. I assume this is the styling not noticing that the instance has changed. Is there anyway to force the View to create a new instance every time the ViewModel changes?

样式:

<DataTemplate DataType="{x:Type vm:SubViewModel}">
    <v:SubView />
</DataTemplate>

MainViewModel:

MainViewModel:

if (DisplayItemControl != null)
{
    DisplayItemControl.Cleanup();
    DisplayItemControl = null;
}
DisplayItemControl = new SubViewModel();

推荐答案

DataTemplate 资源中添加x:Shared="false"应该可以创建一个新实例.当DisplayItemControl直接设置为其新值时,而不是首先将其设置为null时,此方法不起作用,因此我注意到了.

Adding x:Shared="false" to your DataTemplate resource should allow a new instance to be created. This does not work when DisplayItemControl is directly set to its new value, instead of setting it to null first, so I've noticed.

<DataTemplate DataType="{x:Type vm:SubViewModel}" x:Shared="false">
    <v:SubView />
</DataTemplate>

这篇关于创建新的ViewModel实例时,视图状态保持不变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆