Reputation: 24833
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?
Upvotes: 18
Views: 10934
Reputation: 4976
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;
}
Upvotes: 0
Reputation: 1505
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? :)
Upvotes: 2
Reputation: 51
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.
Upvotes: 5
Reputation: 7958
var singleView = regionManager.Regions["MyRegion"].ActiveViews.FirstOrDefault();
Upvotes: 15