首页 > 解决方案 > UC卸载时WPF MVVM处理ViewModel

问题描述

我开始使用 MVVM-Light 构建 WPF 应用程序。我的应用程序有一个顶部菜单栏和一个带有中央面板的左侧菜单栏,其中一些用户控件显示左侧/顶部菜单选项。一切正常,但我的视图模型没有清理/处理;当我从左侧或顶部菜单中选择菜单选项时,我的视图模型仍然存在,当我回到菜单选项时,视图不会刷新并保持插入值。

这是我的代码的一部分:

MainViewModel 从顶部/左侧菜单接收消息并显示 UserControl

public class MainViewModel : ViewModelBase
{
       Messenger.Default.Register<NotificationMessage<string>>(this, "My_Token", (message) =>
        {MessageUtility wMesageUtility = new MessageUtility();
            switch (message.Notification)
            {
                case "MyMessage":
                    switch (message.Content)
                    {
                        case "Insert":
                            if (!SimpleIoc.Default.IsRegistered<Insert_ViewModel>())
                            {
                                SimpleIoc.Default.Register<Insert_ViewModel>(true);
                            }

                            wInsertVM = SimpleIoc.Default.GetInstance<Insert_ViewModel>();
                            ShowMainView(null);
                            CurrentViewModel = wInsertVM;
                            break;
                        default:
                            break;
                    }
                    break;
                default:
                    break;
            }
        });

我的视图模型类:

public class Insert_ViewModel : ViewModelBase
{
    public FormInternal_ViewModel()
    {
       ...Some Code with ICommand and private methods
    }
}

我的 XAML 文件:

<UserControl x:Class="MyApp.UC.Insert"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"              
         xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
         xmlns:cmd="clr-namespace:GalaSoft.MvvmLight.Command;assembly=GalaSoft.MvvmLight.Platform"
         mc:Ignorable="d" 
         d:DesignHeight="400" d:DesignWidth="700"             
         >
<DockPanel Name="MainDock" LastChildFill="True" DataContext="{Binding Insert, Source={StaticResource Locator}}" 
           VerticalAlignment="Stretch" 
           Height="Auto">

    <Grid>
   </Grid>
 </DockPanel>
</UserControl>

选择顶部/左侧菜单时如何处理 Insert_ViewModel?谢谢。

标签: user-controlsviewmodelmvvm-lightdispose

解决方案


推荐阅读