18

I know that i can get all the registered views in a region with :

var vs = mRegionManager.Regions[RegionNames.MainRegionStatic].Views.ToList();

and i can see there is the following code :

mRegionManager.Regions[RegionNames.MainRegionStatic].ActiveViews

which is giving a list of Active View, but I'm having my region attached to a ContentControl which always has a single ActiveView. Am i misunderstood or is there a way to get the single active view?

4 Answers 4

15

var singleView = regionManager.Regions["MyRegion"].ActiveViews.FirstOrDefault();

3
  • Great that worked, but how is it that we have a collection for that? Jun 15, 2011 at 14:27
  • 2
    because SingleActiveRegion inherits Region Jun 15, 2011 at 14:33
  • Is there a way to get existing VMs using the IoC container (in my case DryIoc)? I tried this == _Container.Resolve<ShellViewModel> from the ShellViewModel and it evaluated to false. Nov 27, 2017 at 17:09
5
var singleView = regionManager.Regions["MyRegion"].ActiveViews.FirstOrDefault();

This is not correct, as it will just bring whatever view that got activated first. not the currently active/visible view.

Can't find a direct solution though, that doesn't involve custom implementation on View or ViewModel.

1
  • Interesting !! , but at the time it was what i needed. can you give more details ? Dec 6, 2011 at 21:36
2

Well, you could use the NavigationService Journal. It takes record of all the navigation that takes place in your application. So, you can get the name of the view like this:

string name = mRegionManager.Regions[RegionNames.MainRegionStatic].NavigationService.Journal.CurrentEntry.Uri;

Then you can get the view like this:

mRegionManager.Regions[RegionNames.MainRegionStatic].GetView(name);

Sweet Right? :)

0

Using Xamarin.Forms & Prism, this works well for me. Change the regionName, change the View Model base to yours.

public VisualElement GetCurrentRegionView()
{
    var regionName = "MenuPageRegion";
    var region = RegionManager.Regions[regionName];
    var uri = region.NavigationService.Journal.CurrentEntry.Uri.OriginalString;
    foreach (var view in region.ActiveViews)
    {
        var name = view.GetType().FullName;
        if (name.EndsWith(uri))
            return view;
    }
    return null;
}

public CommonViewModelBase GetCurrentRegionViewModel()
{
    var view = GetCurrentRegionView();
    if (view != null)
    {
        var binding = view.BindingContext;
        if (binding is CommonViewModelBase model)
            return model;
    }
    return null;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.