TheDuke
TheDuke

Reputation: 185

WPF Prism V2 Using M-V-VM - Add a view at runtime to a region from the ViewModel

Hopefully quite a simple one, having my first try at WPF with Prism V2 using M-V-VM and so far finding everything pretty awsome. My Shell is pretty simple, Ribbon Control at the Top, DataGrid of Help desk tickets on the left, and a TabControl on the right.

When a user opens the selected ticket from the datagrid, I want the Ticket to open as a Tab on the Tab Control. I know in order to do that I need to add and then activate the View to the region using the RegionManager. But doing this from the ViewModel doesn't seem correct to me, although I could do it using DI (DepenecyInjection) it still rings alarms in my head about giving the ViewModel some knowledge about a View.

To Add to this, different modules will also be adding other views (Contact, Client etc) into the TabControl, I'd like to use DataTemplates to get the TabControl to display the View Correctly, can anyone give me any pointers for this as well.

Many Thanks Ben

Full answers please, not just links. It's what StackOverflow is for!

Upvotes: 0

Views: 2293

Answers (2)

Cameron MacFarland
Cameron MacFarland

Reputation: 71946

MVVM + Services = Ultimate Power!

A service is just an interface that's well known and is registered in your IOC container. When the ViewModel needs to do something outside of itself, like say open a tabbed document, it uses the service. Then the service is implemented as needed for the particular program.

For example:

public interface IDocumentService
{
    void OpenDocument(IViewModel viewModel);
}

internal class DocumentService:IDocumentService
{
    public void OpenDocument(IViewModel viewModel)
    {
        // Implement code to select the View for the ViewModel,
        // and add it to your TabControl.
    }
}

{
    // Somewhere in your ViewModel...
    // Make sure you can get the IDocumentService
    IDocumentService docService = ioc.Get<IDocumentService>();
    docService.OpenDocument(new TicketViewModel());
}

Upvotes: 1

Ana Betts
Ana Betts

Reputation: 74692

Commands are the way to do this - you'll send a command to yourself, called "RequestBringTicketIntoView"; it will bubble up to the Window, where you handle it. Read Josh Smith's article:

http://joshsmithonwpf.wordpress.com/2008/03/18/understanding-routed-commands/

Upvotes: 0

Related Questions