C# 在ViewModel之外修改ViewModel属性-值为';储蓄

C# 在ViewModel之外修改ViewModel属性-值为';储蓄,c#,mvvm,unity-container,mvvm-light,C#,Mvvm,Unity Container,Mvvm Light,是否可以使用代码中其他地方的ViewModelLocator实例修改ViewModel的属性?当我尝试时,我尝试分配的任何值似乎都会被丢弃 例如,ViewModel,其名为“Game”的实例包含在我的ViewModelLocator中。它有一个名为“Test”的字符串属性。当我尝试以这种方式修改它时: (App.Current.Resources["Locator"] as ViewModelLocator).Game.Test = "Testing"; System.Windows.Messa

是否可以使用代码中其他地方的ViewModelLocator实例修改ViewModel的属性?当我尝试时,我尝试分配的任何值似乎都会被丢弃

例如,ViewModel,其名为“Game”的实例包含在我的ViewModelLocator中。它有一个名为“Test”的字符串属性。当我尝试以这种方式修改它时:

(App.Current.Resources["Locator"] as ViewModelLocator).Game.Test = "Testing";
System.Windows.MessageBox.Show((App.Current.Resources["Locator"] as ViewModelLocator).Game.Test);

消息框显示ViewModel本身中声明的字符串值(如果有)。如果尚未在ViewModel中指定值,则消息框将显示为空。无论哪种方式,它们都不会显示“测试”

我怎样才能做到这一点?我将MVVM Light与Unity一起使用

public class ViewModelLocator
{
    private static Bootstrapper _bootstrapper;

    static ViewModelLocator()
    {
        if (_bootstrapper == null)
            _bootstrapper = new Bootstrapper();
    }

    public GameViewModel Game
    {
        get { return _bootstrapper.Container.Resolve<GameViewModel>(); }
    }
}

public class Bootstrapper
{
    public IUnityContainer Container { get; set; }

    public Bootstrapper()
    {
        Container = new UnityContainer();

        ConfigureContainer();
    }

    private void ConfigureContainer()
    {
        Container.RegisterType<GameViewModel>();
    }
}
公共类ViewModelLocator
{
专用静态引导程序_引导程序;
静态ViewModelLocator()
{
if(_bootstrapper==null)
_引导程序=新引导程序();
}
公共游戏视图模型游戏
{
获取{return _bootstrapper.Container.Resolve();}
}
}
公共类引导程序
{
公共IUnityContainer容器{get;set;}
公共引导程序()
{
容器=新的UnityContainer();
配置容器();
}
私有void配置容器()
{
Container.RegisterType();
}
}

看起来这是统一的问题。我切换回了MVVM Light的SimpleIoc,它可以正常工作。

当您调用
Container.RegisterType()时这将使用默认的生存期管理器注册类型
GameViewModel
。这意味着每次调用
Resolve
,都会返回一个新实例

因此,每次调用
Game
属性时,都会返回
GameViewModel
的一个新实例。对该对象的任何修改只会对该对象进行(并且在对象被GC’d时丢失)。下次调用
Game
属性时,将返回
GameViewModel
的新实例

因此,假设您只需要一个
GameViewModel
,您应该将其注册为单例:

private void ConfigureContainer()
{
    Container.RegisterType<GameViewModel>(new ContainerControlledLifetimeManager());
}
private void ConfigureContainer()
{
RegisterType(新的ContainerControlledLifetimeManager());
}
private void ConfigureContainer()
{
    Container.RegisterType<GameViewModel>(new ContainerControlledLifetimeManager());
}