簡體   English   中英

WPF:ImageSource 相對於可執行位置而不是項目位置

[英]WPF: ImageSource relative to executable location not project location

我想從我的可執行位置下的目錄加載圖像。

<ImageBrush x:Key="WindowBackground" ImageSource="./backgrounds/Zenitsu.png" Stretch="UniformToFill"/>

我曾嘗試使用./backgrounds/\backgrounds\但兩者似乎都直接在項目中查找結果或在可執行文件的位置。

我的 output 結構是這樣的:

Main.exe
----backgrounds
--------Zenitsu.png

您可以創建一個轉換器,例如:

public class PathToExecutableConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (parameter is string path)
        {
            string rootPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
            return Path.Combine(rootPath, path);
        }

        return value;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotSupportedException();
    }
}

並按如下方式使用它:

<Window.Resources>
    <local:PathToExecutableConverter x:Key="PathToExecutableConverter"></local:PathToExecutableConverter>
    <ImageBrush x:Key="WindowBackground"  ImageSource="{Binding ., Converter={StaticResource PathToExecutableConverter}, ConverterParameter=backgrounds/Zenitsu.jpg}" Stretch="UniformToFill"/>
</Window.Resources>

如果圖像不會改變,您可能更願意將它們作為嵌入式資源包含: 如何在 XAML 中引用圖像資源?

暫無
暫無

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

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