One of the Simple and Reasonable Solutions for Prism WPF Login Dialog

One of the Simple and Reasonable Solutions for Prism WPF Login Dialog

This is a very concise short article.

Last updated 1/10/2022 8:08 PM
沙漠尽头的狼
2 min read
Category
WPF
Topic
WPF MVVM Framework Prism Series
Tags
.NET C# WPF Prism

1. Foreword

This is a very short article. First, I would like to thank the site owner and all the WPF experts for their guidance. I have learned a lot. It is still about using Prism to create a Login dialog. I saw that the site owner published an article 《WPF Prism Framework Region Invalid?》. Now I have a solution that I think is more suitable, and I would like to share it with you:

2. Main Content

The essence is one sentence: override the protected override void OnInitialized() method in the main App class, and then write the logic of login.ShowDialog() inside it. See the code below for details:

namespace Wpf1
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App
    {
        protected override Window CreateShell()
        {

             return Container.Resolve<MainWindow>();

        }
        protected override void RegisterTypes (IContainerRegistry containerRegistry)
        {

        }
        protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
        {

        }
        protected override void OnInitialized()
        {
            var login = Container.Resolve<Login>();
            var loginResult = login.ShowDialog();
            if (loginResult.Value)
               base.OnInitialized();
            else
               Application.Current.Shutdown();
        }
    }
}

Then in Login.xaml.cs, write the Click events for the "Login" and "Exit" buttons as follows:

private void Btn1_Click(object sender, RoutedEventArgs e)
{
    // Login
    DialogResult = true;
}
private void Btn2_Click(object sender, RoutedEventArgs e)
{
    // Exit
    DialogResult = false;
}

That's it, very simple. The key point is still to override the protected override void OnInitialized() method in the App, so that MainWindowViewModel is not loaded simultaneously when the Login dialog is shown. However, there is one thing to note: at this point, Prism's Region does not seem to have taken effect. Using Prism's view injection or view discovery to add views to the Login dialog should not work. Fortunately, the Login dialog is usually not very complex, so you can just write it normally in Login.xaml.

Author: Wang Jinghao

WeChat ID: daidai_cn

Keep Exploring

Related Reading

More Articles