Category Archives: Avalonia

Trying out Avalonia

Note: This post was written a while back but sat in draft. I’ve published this now, but I’m not sure it’s relevant to the latest versions etc. so please bear this in mind.

Avalonia is aiming to support a XAML way of implementing cross platform UI’s. Whilst I can use Xamarin Forms for developing on iOS, Android etc. it doesn’t currently support Linux.

So let’s have a look at implementing a very basic Hello World application using Avalonia. This post covers using Visual Studio 2017 (obviously on Windows).

  • Creating a WPF application, mine’s named HelloAvaloniaWorld
  • Remove the following references
    • PresentationCore
    • PresentationFrameworj
    • WindowsBase

    as we’re not using WPF

  • Add NuGet packages
    • Avalonia
    • Avalonia.Desktop

Now replace App.xaml with the following

<Application xmlns="https://github.com/avaloniaui">
    <Application.Styles>
        <StyleInclude Source="resm:Avalonia.Themes.Default.DefaultTheme.xaml?assembly=Avalonia.Themes.Default"/>
        <StyleInclude Source="resm:Avalonia.Themes.Default.Accents.BaseLight.xaml?assembly=Avalonia.Themes.Default"/>
    </Application.Styles>
</Application>

Replace the application class in App.xaml.cs with

using Avalonia;
using Avalonia.Markup.Xaml;

namespace HelloAvaloniaWorld
{
    public class App : Application
    {
        public override void Initialize()
        {
            AvaloniaXamlLoader.Load(this);
        }

        private static void Main()
        {
            AppBuilder.Configure<App>()
                .UsePlatformDetect()
                .Start<MainWindow>();
        }
    }
}

Let’s now alter the MainWindow.xaml to look like

<Window xmlns="https://github.com/avaloniaui">
    <Grid>
        <TextBlock FontSize="16" Text="Hello World"/>
    </Grid>
</Window>

And replace the MainWindow.xaml.cs contents with

using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;

namespace HelloAvaloniaWorld
{
    public class MainWindow : Window
    {
        public MainWindow()
        {
            this.InitializeComponent();
            this.AttachDevTools();
        }

        private void InitializeComponent()
        {
            AvaloniaXamlLoader.Load(this);
        }
    }
}

Before we move on, select each XAML file and display the file properties in Visual Studio, from here, remove the Custom Tool and change the Build Action to Embedded Resource.

From AssemblyInfo.cs remove the section

[assembly: ThemeInfo(...)]

Before the application builds you’ll need to copy the packages\SkiaSharp.1.57.1\build and runtime folders to the solution root folder, into a folder named SkiaSharp\1.57.1.