AvaloniaUtils/DialogHost.Avalonia

How to automatically open a View at startup?

DenisTukhvatshin opened this issue · 4 comments

I need to check some values at startup and after that I need to show or not show the view.
like this in View:

public MainViewModel()
{
    Task.Run(Startup);
}

private bool _isLogged;

private async Task Startup()
{
    if (_isLogged)
    {
    //don't show View
    }
    else
    {
        var loginView = new LoginViewControl();
        await DialogHost.DialogHost.Show(loginView, "MainDialogHost");
    }
}

For some reason, the View is not displayed at startup. Do you have any suggestions on how to do this?

Hello, @DenisT90

I think that current code, what you posted here will throw an exception about no DialogHost with this identifier found. If you put a breakpoint at your DialogHost.Show (or surround it with try catch) you most likely see an exception.

This is happening because your VM most likely created before View was initialized, so there is no DialogHost with this identifier.

I think this is a bit of a complicated problem. I see this solution: you should override OnAttachedToVisualTree (or something like it) in your view and inside it call your VM's Startup method. This should work, I think.

in UserControl it works well with override OnAttachedToVisualTree.
but first I need to check if I need to show View in autorun.
I would like to use the method in the ViewModel and check whether it is required to show or not. How is it more correct to do this?

in UserControl it works well with override OnAttachedToVisualTree.
but first I need to check if I need to show View in autorun.
I would like to use the method in the ViewModel and check whether it is required to show or not. How is it more correct to do this?

in UserControl it works well with override OnAttachedToVisualTree.

Not necessary this will be in UserControl, you can do it inside your main View or Window (where DialogHost located).

I personally prefer ReactiveUI approach - view (viewmodel) activation. So, with this approach you can check your prerequisites and show dialog when necessary inside WhenActivated delegate in view model. But I know that not everyone likes ReactiveUI, so my approach above is about the same, but without using ReactiveUI.

Another approach - set bindings to DialogContent and IsOpen from view model, so when DialogHost will be loaded it will automatically open requested content dialog.

I'm closing issue. If you still have questions, feel free to reopen it or create a new one.