- 1 year ago
UWP Multiple views in single UI Thread
In a Universal Windows Platform (UWP) app, each view runs in its own separate UI thread. However, there are scenarios where you might want to host multiple views within a single UI thread. This can be useful for sharing data, resources, or for implementing custom interactivity between different views.
To host multiple views in a single UI thread in a UWP app, you can use the CoreApplication.CreateNewView
method to create additional views and then use the CoreApplicationViewSwitcher
class to switch between these views. Here's a basic overview of the steps:
Create the main view (usually done in the
OnLaunched
event ofApp.xaml.cs
).Inside the main view, create additional views using
CoreApplication.CreateNewView
and pass a unique view ID.In the main view, use
CoreApplicationViewSwitcher
to switch to a specific view when needed.
Here's some sample code to demonstrate this process:
csharp// Inside App.xaml.cs
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
// Create and activate the main view
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
Window.Current.Content = rootFrame;
}
if (e.PrelaunchActivated == false)
{
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
Window.Current.Activate();
}
}
// Inside MainPage.xaml.cs (Main view)
private async void OpenNewViewButton_Click(object sender, RoutedEventArgs e)
{
int newViewId = 0;
// Create a new view and get its view ID
await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
Frame frame = new Frame();
frame.Navigate(typeof(SecondPage), null);
Window.Current.Content = frame;
Window.Current.Activate();
newViewId = ApplicationView.GetForCurrentView().Id;
});
// Switch to the new view
bool viewSwitched = await CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
return ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
});
}
// Inside SecondPage.xaml.cs (Second view)
private void GoBackButton_Click(object sender, RoutedEventArgs e)
{
// Go back to the main view
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack)
{
rootFrame.GoBack();
}
}
In this example, when the "Open New View" button is clicked in the MainPage, a new view (SecondPage) is created, and the app switches to the new view. When the "Go Back" button is clicked in the SecondPage, the app goes back to the main view.
Keep in mind that while hosting multiple views in a single UI thread can be useful in specific scenarios, it can also introduce complexities. Make sure to carefully manage data synchronization and handle any potential concurrency issues between views.