gpt4 book ai didi

c# - Caliburn.Micro WPF : How can I create a new ViewModel that has a dependency?

转载 作者:行者123 更新时间:2023-12-03 10:32:38 24 4
gpt4 key购买 nike

我创建了一个称为ShellView的窗口,该窗口将加载或处理两个名为AView和BView的用户控件。

我已经有了这个设置:

Bootstrapper.cs

public class Bootstrapper : BootstrapperBase
{
private SimpleContainer _container = new SimpleContainer();

public Bootstrapper()
{
Initialize();
}

protected override void OnStartup(object sender, StartupEventArgs e)
{
base.OnStartup(sender, e);
DisplayRootViewFor<ShellViewModel>();
}

protected override void Configure()
{
_container.Singleton<IWindowManager, WindowManager>();
_container.Singleton<IEventAggregator, EventAggregator>();
_container.RegisterPerRequest(typeof(ShellViewModel), null, typeof(ShellViewModel));
}

protected override object GetInstance(Type serviceType, string key)
{
return _container.GetInstance(serviceType, key);
}

protected override IEnumerable<object> GetAllInstances(Type serviceType)
{
return _container.GetAllInstances(serviceType);
}

protected override void BuildUp(object instance)
{
_container.BuildUp(instance);
}
}

AViewModel.cs
public class AViewModel : Screen
{
private IEventAggregator _eventAggregator;

public AViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator.
}
}

这就是问题所在,如何在ShellViewModel中传递事件聚合器的实例?

ShellView.cs
public class ShellViewModel : Conductor<Screen>
{
public ShellViewModel()
{
// Should I create an instance and pass it in? If not, how?
ActivateItem(new AViewModel(?));
}
}

最佳答案

Caliburn.Micro为此具有一个静态类IoC。您应该执行以下操作:

ActivateItem(IoC.Get<AViewModel>());

或者,如果可行,您可以执行以下操作:
public class ShellViewModel : Conductor<Screen>
{
private IEventAggregator _eventAggregator;

public ShellViewModel(IEventAggregator eventAggregator)
{
_eventAggregator = eventAggregator;
ActivateItem(new AViewModel(_eventAggregator));
}
}

关于c# - Caliburn.Micro WPF : How can I create a new ViewModel that has a dependency?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50563837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com