ViewModels references in ShellViewModel Caliburn.Micro

寵の児 提交于 2019-12-06 15:29:03

Finally, I managed to find an answer myself. It's all in the AppBootstrapper!

I ended up creating a ViewModelBase for my Screens so that they could all have an IShell property (so that the ViewModels could trigger a navigation in the ShellViewModel) like so:

public class ViewModelBase : Screen
{
    private IShell _shell;

    public IShell Shell
    {
        get { return _shell; }
        set
        {
            _shell = value;
            NotifyOfPropertyChange(() => Shell);
        }
    }
}

then in the AppBoostrapper registered them like this :

container.Singleton<ViewModelBase, SomeViewModel>();
container.Singleton<ViewModelBase, AnotherViewModel>();
container.Singleton<ViewModelBase, YetAnotherViewModel>();

then created an IEnumerable to pass as param to my ShellViewModel ctor:

IEnumerable<ViewModelBase> listScreens = GetAllScreenInstances();

container.Instance<IShell>(new  ShellViewModel(listScreens));

then passing the IShell to each ViewModels

foreach (ViewModelBase screen in listScreens)
{
    screen.Shell = GetShellViewModelInstance();
}

for the sake of completeness, here are my GetAllScreenInstances() and GetShellViewModelInstance() :

protected IEnumerable<ViewModelBase> GetAllScreenInstances()
{
     return container.GetAllInstances<ViewModelBase>();
}
protected IShell GetShellViewModelInstance()
{
    var instance = container.GetInstance<IShell>();
    if (instance != null)
        return instance;

    throw new InvalidOperationException("Could not locate any instances.");
}

Here's what my ShellViewModel ctor looks like:

public ShellViewModel(IEnumerable<ViewModelBase> screens )
{         
    Items.AddRange(screens);
}

Hope this can help someone in the future!

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