Avalonia Bind TrayIcon to Codebehind

162 views Asked by At

In my .net Avalonia app I am using the TrayIcon control. But the tooltip of my tray icon should be dynamic (the version of the app).

In my App.xaml file I have the following code:

<TrayIcon.Icons>
    <TrayIcons>
        <TrayIcon Icon="/Assets/AppIcon.ico" ToolTipText="{Binding VersionText}">
            <TrayIcon.Menu>
                <NativeMenu>
                    <NativeMenuItem Header="Close" Click="CloseApp"/>
                </NativeMenu>
            </TrayIcon.Menu>
        </TrayIcon>
    </TrayIcons>
</TrayIcon.Icons>

In my App.xaml.cs I set the version with the following code:

public partial class App : Application
{

    public string VersionText { get; set; } = $"My version is {Assembly.GetExecutingAssembly().GetName().Version}";

    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
    }

    ...
}

But whenever I look at the tooltip, nothing happens. What am I missing? Is there a solution that does not involve Viewmodels?

1

There are 1 answers

0
hazib On BEST ANSWER

I would recommend to use a viewmodel.

But if you dont want then you can set the DataContext after the AvaloniaXamlLoader.

ToolTipText="{Binding VersionText}"

The binding will work after this.

Hope this will help.

public partial class App : Application
{
    public string VersionText { get; set; } = $"My version is {Assembly.GetExecutingAssembly().GetName().Version}";

    public override void Initialize()
    {
        AvaloniaXamlLoader.Load(this);
        this.DataContext = this;
    }
     ...
}