Prism: IRegionMemberLifetime doesn't work in some scenarios
I'm trying to create a Silverlight app using Prism 4, and I'm testing it's navigation abilities. I want to switch between two views when I click on a button. The first view is:
public partial class HomeView
{
public HomeView(HomeViewModel viewModel)
{
DataContext = viewModel;
InitializeComponent();
}
}
and the ViewModel:
public class HomeViewModel : NotificationObject, IRegionMemberLifetime
{
private readonly IRegionManager _regionManager;
public DelegateCommand SubmitCommand { get; set; }
public bool KeepAlive { get { return false; } }
public HomeViewModel(IRegionManager regionManager)
{
_regionManager = regionManager;
SubmitCommand = new DelegateCommand(Submit);
}
private void Submit()
{
_regionManager.RequestNavigate("开发者_JAVA技巧Home", new Uri(typeof(UsersView).Name, UriKind.Relative));
}
}
The problem is that when I set the "Home" region to be on a ItemsControl, Grid (with adapter) - it doesn't enter the KeepAlive property, and just add the second view to the region and I see them both.
When the region is defined to be a ContentControl or a TabControl - it removes the HomeView and add the UsersView!
Can anyone tell me what I'm doing wrong? I want to use a grid as the region to achieve this.
I've read this chapter http://msdn.microsoft.com/en-us/library/gg430861%28v=pandp.40%29.aspx and found no answer...
You've got two types of controls being used:
ContentControl and TabControl will use a Region Adapter using SingleActiveRegion. Basically, only one view can be shown at one time.
The Grid and ItemsControl are probably both AllActiveRegion (ItemsControl is definitely, don't know about your GridAdapter), which means they can display multiple views at once.
Looking at the NavigationService, which is what the Region uses to move from view X to view Y, this is what happens:
Notifies the active view that it's no longer active.
Loads up the new view. If it's already there (and the view implements IActiveAware) it will reactiveate it. Otherwise it creates a new instance of the view
Fires the Navigating Event
Informs the "y" view that it's being navigated to. Again, the view must implement IActiveAware
Raises the NavigatedEvent.
So:
Do your views implement IActiveAware?
More importantly, if you're using a container that can show multiple views at once (ItemsControl, etc) then I think you'll need to manually remove the view from the Region because Prism isn't going to do it for you!
You can actually do this fairly easily. You can write your own class that implements INavigationService and then insert this into the NavigationService property of the Region. This gives you control of what the navigation service is doing.
Hope this helps.
精彩评论