Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 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 Reply

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...