A proper MVVM-style way to add a Button to Toolbar from Prism module

329 Views Asked by At

I have composite application with toolbar and I want to make my modules possible to add some buttons to toolbar. As I have understood, a RegionManager should be used to provide this possibility.

I wrote a code like this:

public class MyModule : IModule
{
    private readonly IUnityContainer _container;
    public MyModule(IUnityContainer Container) { _container = Container; }

    public void Initialize()
    {
        var regionManager = _container.Resolve<RegionManager>();
        regionManager.RegisterViewWithRegion("MainToolbar",
                                             () => new Button
                                                   {
                                                       Content = "My Button",
                                                       Command = new DelegateCommand(/*  */)
                                                   });
    }
}

But it seems like creating a buttons from code, especially inside of Module class is not a good idea, according the MVVM pattern. And the second problem is that the button is being created before other modules would be initialized, so I can't refer to services registred by other modules.

What exactly I'm doing wrong? What is a propper way to collect actions from multiple modules into one toolbar?

1

There are 1 best solutions below

0
Haukinger On

Your idea is correct, just swap out the button for a view that contains a button. Then make the toolbar a region and inject the "button"-view into the "toolbar"-region.

If your module depends on services that come from other modules, make your module dependent on those modules, so that prism makes sure that the services are initialized first:

[ModuleDependency("ServiceModule")]
public class ModuleA : IModule
{
    ...
}

public class ServiceModule : IModule
{
    ...
}