NullReferenceException when closing and opening windows in Avalonia MVVM application

34 views Asked by At

I am developing a desktop application using Avalonia UI with the MVVM pattern, and I am encountering a NullReferenceException when attempting to close a login window and open the main window after successful authentication. I've checked that the LoginWindow property in my LoginWindowViewModel should be set with a reference to the current window, but it remains null.

Code LoginWindow.xaml.cs:

public LoginWindow()
{
    InitializeComponent();
    var viewModel = new LoginWindowViewModel();
    DataContext = viewModel;
    viewModel.LoginWindow = this;
}

LoginWindowViewModel.cs:

public class LoginWindowViewModel : ViewModelBase
{
    public Window LoginWindow { get; set; }

    // Properties and methods...

    public void MainWindowOpen()
    {
        var mainWindow = new MainWindow();
        mainWindow.Show();
        LoginWindow.Close(); // Line 63, NullReferenceException occurs here
    }

    [RelayCommand]
    private void WrongUsernameOrPassword()
    {
        // Authentication logic...
        if (authSuccess)
        {
            MainWindowOpen(); // Line 53
        }
        else
        {
            WarningSign = true;
        }
    }
}

Issue:

When the WrongUsernameOrPassword method is executed, and if the authentication is successful, the MainWindowOpen() method is called. This should show the main application window and close the current login window. However, when MainWindowOpen() attempts to close LoginWindow, a System.NullReferenceException is thrown, indicating that LoginWindow is null.

I confirmed through debugging that viewModel.LoginWindow = this; is being executed in the LoginWindow constructor, and the ViewModel is assigned to DataContext. But when stepping through the code, LoginWindow is null at the point of calling Close() on it in the MainWindowOpen() method.

Question: Why is the LoginWindow property null when accessed in the MainWindowOpen() method, despite being set in the LoginWindow constructor? How can I ensure that LoginWindow retains the reference to the window so that it can be closed properly?

  • Ensuring viewModel.LoginWindow = this; is set after DataContext is assigned in the LoginWindow constructor.
  • Debugging with breakpoints to confirm the order of property setting and method calls.
  • Checking for any code that might inadvertently set LoginWindow to null.
0

There are 0 answers