AvaloniaUtils / DialogHost.Avalonia

AvaloniaUI control that provides a simple way to display a dialog with information or prompt the user when information is needed
MIT License
228 stars 15 forks source link

How to automatically open a View at startup? #11

Closed DenisTukhvatshin closed 1 year ago

DenisTukhvatshin commented 1 year ago

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?

SKProCH commented 1 year ago

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.

DenisTukhvatshin commented 1 year ago

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?

SKProCH commented 1 year ago

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.

SKProCH commented 1 year ago

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