0

我有一个用 Avalonia 类库编写的 ContentControl/TemplatedControl,以及在文件中定义的样式。

要在 WPF 中加载样式,您需要使用此 hack 添加 AssemblyInfo.cs

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)
)]

现在有了Avalonia......有什么办法呢?

编辑:客户端必须在 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>

但是——如果我想用不同的样式显示多个这样的控件怎么办?我可以在控件上有一个属性来选择主题或颜色。

4

1 回答 1

1

中定义的样式App.xaml是全局的,因此所有控件都将使用它们。但是,可以在运行时更改它们。在您的情况下,您可以从创建样式字典开始以简化事物并在那里添加所有内容StyleInclude,因此您Application.Styles只有一个条目:

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

现在,假设您想YourStyles2.xaml在代码中将此资源更改为。

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;
}
于 2021-11-26T14:12:42.490 回答