View state remains the same when a new ViewModel instance is created MVVM

情到浓时终转凉″ 提交于 2019-12-12 02:50:10

问题


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?

Style:

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

MainViewModel:

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

回答1:


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>


来源:https://stackoverflow.com/questions/26119077/view-state-remains-the-same-when-a-new-viewmodel-instance-is-created-mvvm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!