I am a total beginner with WinUI, but have some experience with C# and Windows Forms. I am trying out WinUI 3 for the first time and am trying to open a login window (ContentDialog) before the MainWindow loads. I am using the Template Studio for WinUI. And have created a test application.
I would like to open a ContentDialog when the program is started and a user logs in. At the moment it is only possible to open the dialog from a page (view) (see question from @WalderFrey and the answer from @mm8 to the Stackoverflow question (Link).
But this has the consequence that every time I click on the page, the login dialog appears.
How can I open the dialog at startup and only once without having to create a complicated logic. Is this possible in the MainWindow or via App.xaml?
Page1.xml
using System.Runtime.InteropServices;
using login_test.ViewModels;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
namespace login_test.Views;
public sealed partial class page1Page : Page
{
public page1ViewModel ViewModel
{
get;
}
public page1Page()
{
ViewModel = App.GetService<page1ViewModel>();
InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
var dlg = new ContentDialog();
dlg.XamlRoot = this.XamlRoot;
dlg.Content = new LoginPage();
dlg.PrimaryButtonText = "Login";
dlg.CloseButtonText = "Cancel";
dlg.DefaultButton = ContentDialogButton.Primary;
var result = await dlg.ShowAsync();
if (result == ContentDialogResult.Primary)
{
}
else if (result == ContentDialogResult.Secondary)
{
Application.Current.Exit();
}
else
{
Application.Current.Exit();
}
}
}
LoginPage.xaml
<?xml version="1.0" encoding="utf-8" ?>
<Page
x:Class="login_test.Views.LoginPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="using:login_test.Views"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
Background="#00FFFFFF"
mc:Ignorable="d">
<StackPanel>
<Image Width="130" Source="/Assets/RIAM_logo.png" />
<TextBlock
Margin="0,10,0,25"
HorizontalAlignment="Center"
VerticalAlignment="Center"
FontFamily="Arial Black"
FontSize="26"
Text="IMS Login" />
<TextBox
Name="usernameTB"
Margin="5,0,5,10"
PlaceholderText="Username" />
<PasswordBox
Name="passwordTB"
Margin="5,0,5,0"
PlaceholderText="Password" />
</StackPanel>
</Page>
As it's mentioned in the comments, the
ContentDialogneeds aXamlRoot. Unfortunately,Windows do not have aXamlRoot.Since you just need a login window and you are using WinUIEx from the TemplateStudio, you can create a login window like this:
LoginWindow.xaml
LoginWindow.xaml.cs
IAuthenticationService.cs
AuthenticationService.cs
and in use it before you activate the
MainWindow:App.xaml.cs