创建一个ResourceDictionary
<ResourceDictionary xmlns="https://github.com/avaloniaui" xmlns:local="using:AvaloniaUI.Demos.Book._10" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"> <!-- Add Resources Here --> <ImageBrush x:Key="{x:Static local:CustomResources.SadTileBrushKey}" Source="avares://AvaloniaUI/Resources/Images/sadface.jpg" TileMode="Tile" DestinationRect="0 0 32 32" Opacity="0.3" /> </ResourceDictionary>
对应的CustomResources类代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AvaloniaUI.Demos.Book._10
{
public class CustomResources
{
public static readonly string SadTileBrushKey = "SadTileBrush";
}
}
ResourceFromLibrary.axaml代码
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" Height="300" Width="300" x:Class="AvaloniaUI.ResourceFromLibrary" xmlns:local="using:AvaloniaUI.Demos.Book._10" Title="ResourceFromLibrary"> <Window.Resources> <ImageBrush x:Key="TileBrush" Source="avares://AvaloniaUI/Resources/Images/happyface.jpg" TileMode="Tile" DestinationRect="0 0 32 32" Opacity="0.3" /> </Window.Resources> <StackPanel Margin="5"> <Button Background="{StaticResource TileBrush}" Padding="5" FontWeight="Bold" FontSize="14" Margin="5"> A Resource From This Assembly</Button> <Button Background="{DynamicResource {x:Static local:CustomResources.SadTileBrushKey}}" Padding="5" Margin="5" FontWeight="Bold" FontSize="14"> A Resource From ResourceLibrary </Button> </StackPanel> </Window>
ResourceFromLibrary.axaml.cs代码 - 动态加载资源
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using System;
namespace AvaloniaUI;
public partial class ResourceFromLibrary : Window
{
public ResourceFromLibrary()
{
InitializeComponent();
this.Resources.MergedDictionaries.Add(this.LoadGeneric());
}
public ResourceDictionary LoadGeneric()
{
return (ResourceDictionary)AvaloniaXamlLoader.Load(
new Uri("avares://AvaloniaUI/Resources/Themes/generic.axaml"));
}
}
运行效果

浙公网安备 33010602011771号