Reputation: 111
Is it possible to check which view is being used inside a region? I'm using MVVM.
I got this code at the moment:
Application.Current.Dispatcher.InvokeAsync(() =>
{
var countactiveviews = RegionManager.Regions.First(x => x.Name == "MainRegion").ActiveViews;
if (!countactiveviews.Any())
{
//// Show preview
var modulePreview = new Uri(_view.Replace("GridView", "Preview"), UriKind.Relative);
RegionManager.RequestNavigate(Regions.PropertiesRegion, modulePreview);
}
else
{
}
When _view is being used or open at the moment, then I want to execute that code again.
So inside my else:
if(_view is being viewed) ...
Any ideas?
Upvotes: 1
Views: 1110
Reputation: 31
It depends on a destination where you want to execute your code.
If you are inside a view model, u can put interface IActiveAware on your view model. It's provide to you property IsActive and event IsActiveChanged.
If you are outside the view model, you can use RegionManager. In each Region are Views and ActiveViews collection. You can check ActiveViews collection for your view model. Also you can use INotifyCollectionChanged interface for detect active view collection changed. Next what can help you is interface INavigationAware. Put it on your view model. There is a method bool IsNavigationTarget(NavigationContext ...) which help you identify your view. Also let use OnNavigatedFrom method to store NavigationContext parameters, and later use it in IsNavigationTarget method.
Here is example:
class MyViewModel : INavigationAware
{
NavigationContext navigationContext;
void OnNavigatedFrom(NavigationContext navigationContext)
{
this.navigationContext = navigationContext;
}
bool IsNavigationTarget(NavigationContext navigationContext)
{
return Equals(this.navigationContext.Uri, navigationContext.Uri);
}
void OnNavigateTo(NavigationContext navigationContext)
{
}
}
...
// somewhere where you need execute
INotifyCollectionChanged activeViews = RegionManager.Regions["MainRegion"].ActiveViews as INotifyCollectionChanged;
if (activeViews!=null)
{
activeViews.CollectionChanged += ActiveViews_CollectionChanged;
}
...
Uri modulePreview;
void ActiveViews_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
IViewsCollection activeViews = (IViewsCollection)sender;
NavigationContext navigationContext=new NavigationContext(null, modulePreview);
activeViews.Any( x=> ((INavigationAware)x).IsNavigationTarget(navigationContext));
}
Upvotes: 2