简体   繁体   English

Caliburn.Micro将已解析的ViewModel实例从父级分配给子级

[英]Caliburn.Micro assign resolved ViewModel instance to child from parent

controls:TabControlView is a reusable component. controls:TabControlView是可重用的组件。 I would need to be able to create a ViewModel/retrieve its instance for each component usage. 我将需要能够为每个组件用法创建一个ViewModel /检索其实例。

<UserControl x:Class="App.Views.Shell.ShellView" ...>
    <StackPanel Orientation="Vertical">

        <controls:TabControlView cal:Bind.Model="{Binding TabControlViewModel}"/>

    </StackPanel>
</UserControl>

In ShellViewModel constructor: 在ShellViewModel构造函数中:

public TabControlViewModel TabControlViewModel { get; set; }
public ShellViewModel(){
    TabControlViewModel = new TabControlViewModel();//For simplicity. It is resolved by IoC
}

When I put a break point into TabControlViewModel's constructor I can see that it is being called 2 times. 当我在TabControlViewModel的构造函数中放置一个断点时,我可以看到它被调用了2次。

When I setup IoC to resolve TabControlViewModel as singleton it works (as the internal call for resolving TabControlViewModel is served the same instance). 当我设置IoC来将TabControlViewModel解析为单例时,它可以工作(因为解析TabControlViewModel的内部调用是在同一实例中进行的)。

How should I edit my code so it doesn't call BootstrapperBase.GetInstance() automatically or how can I replace the View's ViewModel? 我应该如何编辑我的代码,使其不自动调用BootstrapperBase.GetInstance()或如何替换View的ViewModel?

I found out that as the ViewModel is resolved by Caliburn it is then automatically injected to property: 我发现,由于Caliburn解析了ViewModel,然后将其自动注入属性:

public TabControlViewModel TabControlViewModel { get; set; }

All I needed to do is to make it propfull and do setup of the handed instance there: 我需要做的就是使其变得完整,并在那里设置实例。

private TabControlViewModel _tabControlViewModel;

public TabControlViewModel TabControlViewModel
{
    get { return _tabControlViewModel; }
    set
    {
        _tabControlViewModel = value;
        //Init here
        NotifyOfPropertyChange(() => TabControlViewModel);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM