How I solved similar problem for myself, taking advantage of Dependency Injection:
I used Unity and registered dependency to 'Func':
public partial class App
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
IUnityContainer container = new UnityContainer();
container.RegisterType<EntityCRUDWindowViewModel>();
container.RegisterType<ConsumerViewModel>();
container.RegisterInstance<Func<Entity, EntityCRUDWindow>>(entity => new EntityCRUDWindow(){DataContext=container.Resolve<EntityCRUDWindowViewModel>(new ParameterOverride("entity", new InjectionParameter<Entity>(entity))));
/* whatever goes here */
}
}
ViewModel for the CRUD window looks like
public class EntityCRUDWindowViewModel
{
private readonly Entity entity;
public EntityCRUDWindowViewModel(Entity entity)
{
this.entity = entity;
}
}
and you can get the instance of window EntityCRUDWindow
and use it in ConsumerViewModel
or any other ViewModel by simply declaring in constructor parameter
public class ConsumerViewModel
{
public ConsumerViewModel(Func<Entity, EntityCRUDWindow> entityCrudWindowFactory)
{
this.WhateverCommand = new DelegateCommand(
() =>
{
Entity someEntity = null; //or whatever
entityCrudWindowFactory(someEntity).ShowDialog();
});
}
public ICommand WhateverCommand { get; }
}
Thus, you can put any dependency you need in constructor parameters of both viewmodels, just keeping in mind that Entity entity
parameter must be present in EntityCRUDWindowViewModel
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…