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?

pangabiMC
  • 784
  • 5
  • 20
Ehsan Zargar Ershadi
  • 24,115
  • 17
  • 65
  • 95

4 Answers4

15

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

Navid Rahmani
  • 7,848
  • 9
  • 39
  • 57
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.

competent_tech
  • 44,465
  • 11
  • 90
  • 113
Ahmed
  • 51
  • 1
  • 1
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? :)

Prince Owen
  • 1,225
  • 12
  • 20
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;
}
djunod
  • 4,876
  • 2
  • 34
  • 28