If you're using MVVM, one option that's worked for me is to use a combination of
DataTemplate
and a
ContentControl
.
The
ContentControl
's
Content
property is bound to a property on the viewmodel typed as
object
. That property gets set to an instance of a specific viewmodel class representing the page I want to display. The
DataTemplate
for that viewmodel class uses a
UserControl
to display the page.
For example:
MainWindow.xaml
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:views="clr-namespace:..."
xmlns:vm="clr-namespace:..."
...
>
<Window.Resources>
<DataTemplate DataType="{x:Type vm:MainWindowLoadingViewModel}">
<views:MainWindowLoadingView />
</DataTemplate>
<DataTemplate DataType="{x:Type vm:MainWindowAccessDeniedViewModel}">
<views:MainWindowAccessDeniedView/>
</DataTemplate>
...
</Window.Resources>
<ContentControl Content="{Binding Path=CurrentPage}" />
</Window>
MainWindowViewModel.cs
public class MainWindowViewModel : ViewModelBase
{
private object _currentPage = new MainWindowLoadingViewModel();
public object CurrentPage
{
get { return _currentPage; }
private set { SetProperty(ref _currentPage, value); }
}
private void OnLoaded()
{
if (!UserCanAccessApplication)
{
CurrentPage = new MainWindowAccessDeniedViewModel();
return;
}
...
}
}