Search code examples
dialogmodal-dialogavaloniaui

How to open Dialog from Console App in Avalonia


I have a Console Application that, at some point, creates a WPF Window, adds VM to Datacontext, and shows window as Dialog. Console runs Further with DialogResult.

I tried the same with Avalonia, but did not get it working. All Examples work with App.axaml an the AppBuilder (That works, if i want an GUI only App)

When I create the Window as in WPF, I got Exceptions that IWindowPlatform can not be located.

Can I do that in Avalonia?

int main()
{
    var x = foo();
    // some Initiative code
    var view = MyView();
    var viewModel = MyViewModel(x);
    view.DataContext = viewModel;
    var result = view.ShowDialog();
    if(result==DialogResult.Ok)
    {
        var y = viewModel.Bar;

    }
}

Solution

  • This helper does the job, but Looks not as intended:

    using System;
    using Avalonia;
    using Avalonia.Controls;
    using Avalonia.ReactiveUI;
    
    namespace Foo
    {
        public class DialogService
        {
            private readonly Func<Window> windowFactory;
    
            public DialogService(Func<Window> windowFactory)
            {
                this.windowFactory = windowFactory;
            }
            public static AppBuilder BuildAvaloniaApp()
                => AppBuilder.Configure<App>()
                    .UsePlatformDetect()
                    .LogToTrace()
                    .UseReactiveUI();
    
            internal void ShowDialog()
            {
                BuildAvaloniaApp()
                .Start(AppMain, Array.Empty<string>());
            }
    
            private void AppMain(Application app, string[] args)
            {
                var window = windowFactory();
                window.Show();
                app.Run(window);
            }
        }
    }