Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
288 views
in Technique[技术] by (71.8m points)

c# - SimpleChildWindows binded to View Model

I'm using MVVM Light, MahApps and SimpleChildWindows.

I want to be able to create a CRUD Form in a modal popup.

This CRUD form must be binded to its own ViewModel and called by a command in another ViewModel.

I don't succeed to do this with SimpleChildWindows...

So... Is it possible?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...