Avalonia: ViewModel, ViewModelLocator, AvaloniaXamlLoader.Load, Duplication

Created on 25 Sep 2019  路  3Comments  路  Source: AvaloniaUI/Avalonia

After much frustration and days spent on debugging, I tracked what seemed like a networking bug in my program, down to AvaloniaXamlLoader.Load

The loader does not seem to respced DataContext="{Binding MainViewModel, Source={StaticResource Locator}}"

It creates a duplicate view model, calling the constructor twice, and making view model initializations into a big mess

My workaround follows... Although, after further inspection, it looks as if this _hack_ will have to be applied to every view model, until @AvaloniaUI fixes the bug

public class MainViewModel : ViewModelBase {
    private static int passCount;

    public MainViewModel() {
        passCount++;
        if (passCount == 2)
            // initialize only after the first (dummy) pass
            Initialize();
    }

    private void Initialize() {
        // network instantiation, and stuff...
    }
}

Most helpful comment

You are probably using Design.DataContext alongside with a regular DataContext property and are using Avalonia 0.8.x. Unfortunately with Portable.Xaml we couldn't conditionally exclude values from being evaluated. Either switch to d:DataContext which is stripped on XML parsing phase or update to nightly builds where our XAML compiler understands how to handle both of those.

All 3 comments

You are probably using Design.DataContext alongside with a regular DataContext property and are using Avalonia 0.8.x. Unfortunately with Portable.Xaml we couldn't conditionally exclude values from being evaluated. Either switch to d:DataContext which is stripped on XML parsing phase or update to nightly builds where our XAML compiler understands how to handle both of those.

Thanks guys.

I changed it from the Design.DataContext notation the to d:DataContext notation, and now everything is working smoothly.

_As for nightly-builds, I got errors about System.Reactive version downgrade. I manually entered the higher version, but then I got null reference errors after that. So that was a non-starter._

Was this page helpful?
0 / 5 - 0 ratings

Related issues

CreateLab picture CreateLab  路  3Comments

MiKaMaru picture MiKaMaru  路  4Comments

MarchingCube picture MarchingCube  路  4Comments

danwalmsley picture danwalmsley  路  4Comments

MarchingCube picture MarchingCube  路  4Comments