簡體   English   中英

在 Avalonia 的應用程序資源中將圖像路徑設置為變量以供重用

[英]Set image path as variable in the application resources of Avalonia for re-using

我有一個徽標,在我的應用程序的某些地方使用。 所以我想將它的路徑存儲在我的App.axaml文件的變量中,這應該允許我在整個應用程序中將此路徑作為變量引用。 這適用於 colors,如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>元素中的硬編碼路徑?

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

但是,BitmapImage 在 Avalonia 中不可用,但您可以使用 ImageBrush 作為替代方案,請參閱這個很好的示例: https://github.com/AvaloniaUI/Avalonia/issues/7211#issuecomment-998036759

僅稍微調整示例以適應您的用例,您可以在 App.axaml 中定義Logo ,如下所示:

<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}" />

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM