【问题标题】:WPF: ImageSource relative to executable location not project locationWPF:ImageSource相对于可执行位置而不是项目位置
【发布时间】:2021-05-22 10:29:24
【问题描述】:

我想从我的可执行位置下的目录加载图像。

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

我曾尝试使用./backgrounds/\backgrounds\,但两者似乎都直接在项目中查找结果,而不是在可执行文件的位置。

我的输出结构是这样的:

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

【问题讨论】:

    标签: c# wpf xaml imagesource imagebrush


    【解决方案1】:

    您可以创建一个转换器,例如:

    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>
    

    如果图像不会更改,您可能更愿意将它们作为嵌入式资源包含:How to reference image resources in XAML?

    【讨论】:

    • 非常感谢。实际上它们都是 4k 壁纸,真正影响我的应用程序的加载速度。
    • 您可以查看应用程序启动时异步加载图像
    猜你喜欢
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 2023-03-10
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多