benruehl / adonis-ui

Lightweight UI toolkit for WPF applications offering classic but enhanced windows visuals
https://benruehl.github.io/adonis-ui/
MIT License
1.69k stars 143 forks source link

[Support request] AdonisUI styling not applying to codebehind-generated control? #206

Closed ividyon closed 5 months ago

ividyon commented 6 months ago

I have code like this:

private FrameworkElement CreateView(ViewModelBase vm, Type? v)
    {
        if (v != null)
        {
            return (FrameworkElement)Activator.CreateInstance(v)!;
        }
        else
        {
            var name = DeriveViewNameFromViewModel(vm);
            var type = Type.GetType(name);

            if (type != null)
            {
                return (FrameworkElement)Activator.CreateInstance(type)!;
            }

            return new TextBlock { Text = name };
        }
    }

based on the Avalonia ViewLocator class.

Unfortunately it seems that any elements created in this way do not have the AdonisUI styling properly applied. They appear incorrect at first render.

2023-12-28_19-52-27__RainbowStoneMVVM

As you can see, the text in the middle is black instead of white, as it should be in the dark mode theme.

Now, if I press my button which triggers a Dark Mode toggle, on/off...

    [RelayCommand]
    private void DarkMode()
    {
        ResourceLocator.SetColorScheme(Application.Current.Resources, IsDarkMode ? ResourceLocator.LightColorScheme : ResourceLocator.DarkColorScheme);
        IsDarkMode = !IsDarkMode;
    }

The text appears correctly again!

2023-12-28_19-53-25__RainbowStoneMVVM

But until then it is incorrect.

How could I avoid this and have it render correctly right away?

ividyon commented 5 months ago

For anyone else looking for this:

It seems to have happened because I was not using UserControl as the parent of my new controls. I tried to create shortcuts and change the parent element to something like ContentControl, and that is what was causing the breakage.

Putting a ContentControl child into a UserControl and manipulating that instead seems to restore all the resource inheritance, since apparently InitializeComponent() in UserControl is what applies the resources.