Search code examples
c#wpfmoduleprismregion

How to activate the next or last view of a region?


In my application, I'm using Prism and it loads three modules by discovery (Unity).

When the modules are loading, they register each View in "TopLeftRegion" region.

I'm trying to perform a navigation of module views. I mean, create Before and Next methods where can activate (or ["TopLeftRegion"].Activate(..)) the current view in that region.

For example, Imagine I have:

|_ModuleA
|
|_ModuleB
|
|_ModuleC

If my current view is ModuleA, if I press Next, must show ModuleB, if I press Before must show ModuleA in that region.

I was watching the property:

regionManager.Regions["TopLeftRegion"].Views

But I don't know to do this. The property View doesn't allow to access to the data and move into it.

Here's a simple project, I'm trying to create that method in ShellViewModel and I don't get it. How can I do to navigate each module?

http://www.mediafire.com/?urnrwkrb29osrle


Solution

  • Prism doesn't assume that there is only one active view in a region, so there aren't any properties on the Region class that make this super simple. But it isn't too tricky.

    The RegionManager class tracks which views are active in the ActiveViews property. It isn't tracking which one view is active. In your case, your region only supports one active view, so you can just find the first view in that collection.

    The other tricky part is finding the active view in the Region.Views collection. Below I cast the Region.Views as a List so that I could use FindIndex to locate the index of that active view.

        private void Next(object commandArg)
        {
            IRegion myRegion = _regionManager.Regions["TopLeftRegion"];
            object activeView = myRegion.ActiveViews.FirstOrDefault();  //Here we're trusting that nobody changed the region to support more than one active view
            List<object> myList = myRegion.Views.ToList<object>();      //Cast the list of views into a List<object> so we can access views by index
    
            int currentIndex =  myList.FindIndex(theView => theView == activeView);
            int nextIndex = (currentIndex + 1) % (myList.Count);        //Wrap back to the first view if we're at the last view
            object nextView = myList[nextIndex];
            myRegion.Activate(nextView);  
        }
    

    Navigating to the previous view would be mostly the same, except you'd subtract one from the index instead of adding one.