Search code examples
c#-4.0mefprism-4

Activating views in regions in Prism


I have problem that I don't seem to be able to solve. I have a created a test project, using MEF and Prism4. I've created a test project where I have 2 views and each of them register themselves inside a region, and also a button in another region. When the button is clicked, I want the view of change to the correct view. The code I think is wrong is below, anyone have any ideas what I am doing wrong here ?

    public void Initialize()
    {
        regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(Views.Module1View));

        Button button = new Button() { Content = "Module1" };
        button.Click += (o, i) =>
        {
            var region = this.regionManager.Regions[RegionNames.MainRegion];
            if (region != null)
            {
                region.Activate(typeof(Views.Module1View));
            }
        };

        regionManager.AddToRegion(RegionNames.NavigationRegion, button);
    }

I get the following error ...

The region does not contain the specified view.
Parameter name: view

Solution

  • Solved it - amazing what a good nights sleep will do! I had to get the view from the ServiceLocator.

        public void Initialize()
        {
            regionManager.RegisterViewWithRegion(RegionNames.MainRegion, () => 
                ServiceLocator.Current.GetInstance<Views.Module2View>());
    
            Button button = new Button() { Content = "Module2" };
            button.Click += (o, i) =>
            {
                var view = ServiceLocator.Current.GetInstance<Views.Module2View>();
    
                var region = this.regionManager.Regions[RegionNames.MainRegion];
                if (region != null)
                {
                    region.Activate(view);
                }             
            };
    
            regionManager.AddToRegion(RegionNames.NavigationRegion, button);
        }