Home > Blockchain >  Where to Load ContentControl Styles in Avalonia Class Library?
Where to Load ContentControl Styles in Avalonia Class Library?

Time:11-26

I have a ContentControl/TemplatedControl written in Avalonia Class Library, and the styles defined in a file.

To load the styles, in WPF, you'd need to add AssemblyInfo.cs with this hack

using System.Windows;

[assembly: ThemeInfo(
    ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located
                                     //(used if a resource is not found in the page,
                                     // or application resource dictionaries)
    ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located
                                              //(used if a resource is not found in the page,
                                              // app, or any theme specific resource dictionaries)
)]

Now with Avalonia... what's the way to do it?

EDIT: Is the answer that the client must register the files manually in App.xaml?

<Application.Styles>
    <StyleInclude Source="avares://Avalonia.Themes.Default/DefaultTheme.xaml"/>
    <StyleInclude Source="avares://Avalonia.Themes.Default/Accents/BaseLight.xaml"/>
    <StyleInclude Source="avares://Avalonia.Controls.DataGrid/Themes/Default.xaml"/>
</Application.Styles>

but then -- what if I want to display multiple such controls with different styles? I could have a property on the control to choose the theme or the colors.

CodePudding user response:

The styles defined in the App.xaml are global, so all controls will be using them. However, it is possible to change them at runtime. In your case you could start with creating a styles dictionary to simplify things and add all those StyleInclude there, so your Application.Styles have only one entry:

<Application.Styles>
    <StyleInclude Source="avares://YourAssembly/Path/YourStyles1.xaml"/>
</Application.Styles>

Now, let's say you want to change this resource to YourStyles2.xaml in the code.

private static StyleInclude CreateStyle(string url)
{
    var self = new Uri("resm:Styles?assembly=YourAssembly");
    return new StyleInclude(self)
    {
        Source = new Uri(url)
    };
}

private void SetStyles()
{
   var newStyles = CreateStyle("avares://YourAssembly/Path/YourStyles2.xaml");
   Avalonia.Application.Current.Styles[0] = newStyles;
}
  • Related