0

我有一个徽标,在我的应用程序的某些地方使用。所以我想将它的路径存储在我的App.axaml文件的一个变量中,这应该允许我在整个应用程序中引用这个路径作为变量。这适用于像这样的颜色StepBoxBG

<Application.Resources>
    <Color x:Key="StepBoxBG">#5eba00</Color>
    <Image x:Key="LogoPath">/Assets/Logos/logo.png</Image>
</Application.Resources>

DynamicResource在例如这样的边框元素中引用它

<Border Background="{DynamicResource StepBoxBG}" Padding="20">
...
</Border>

但是当我的标志路径以同样的方式被引用时

<Image Height="90" Source="{DynamicResource LogoPath}" />

不显示徽标。路径是正确的,因为当我直接在Image元素中使用路径时,它可以工作:

<Image Height="90" Source="/Assets/Logos/logo.png" />

我发现了这个问题并尝试了它,所以App.axaml看起来像这样:

<Application xmlns="https://github.com/avaloniaui"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="using:My.App"
             xmlns:imaging="clr-namespace:Avalonia.Media.Imaging;assembly=Avalonia.Visuals"
             x:Class="ULabs.Image2Card.App">
    <Application.DataTemplates>
        <local:ViewLocator/>
    </Application.DataTemplates>

    <Application.Styles>
        <FluentTheme Mode="Light"/>
    </Application.Styles>

    <Application.Resources>
        <Color x:Key="StepBoxBG">#5eba00</Color>
        <imaging:Bitmap x:Key="LogoPath">
            <x:Arguments>
                <x:String>/Assets/Logos/logo.png</x:String>
            </x:Arguments>
        </imaging:Bitmap>
    </Application.Resources>
</Application>

现在它抛出一个异常,因为它把它称为绝对路径而不是相对于项目:

System.IO.DirectoryNotFoundException:“找不到路径 'C:\Assets\Logos\logo.png' 的一部分。”

我将构建操作设置为,AvaloniaResource因此它应该包含在我的程序集中。也试过<x:String>Assets/Logos/ul-logo.png</x:String>了,现在异常是指调试文件夹(bin/Debug/net5.0/Assets)。

如何指定仅包含/Assets/Logos/logo.png路径的资源并将其解析为<Image>元素中的硬编码路径?

4

1 回答 1

0

您不能在 <Application.Resources> 中使用 Control 子类 (Image)。在 WPF 中,您通常会使用 BitmapImage。

但是,BitmapImage 在 Avalonia 中不可用,但您可以使用 ImageBrush 作为替代方案,请参阅这个很好的示例: https ://github.com/AvaloniaUI/Avalonia/issues/7211#issuecomment-998036759

仅根据您的用例稍微调整示例,您可以Logo在 App.axaml 中定义如下:

<Application.Resources>
    <Color x:Key="StepBoxBG">#5eba00</Color>
    <ImageBrush x:Key="Logo" Source="/Assets/Logos/logo.png" />
</Application.Resources>

最后,人们会以这种方式引用它:

<Image Height="90" Source="{Binding Source={StaticResource Logo}, Path=Source}" />
于 2022-01-14T22:04:33.690 回答