我想从我的可执行位置下的目录加载图像。
<ImageBrush x:Key="WindowBackground" ImageSource="./backgrounds/Zenitsu.png" Stretch="UniformToFill"/>
我曾尝试使用./backgrounds/or\backgrounds\但两者似乎都直接在项目中查找结果或在可执行文件的位置。
我的输出结构是这样的:
Main.exe
----backgrounds
--------Zenitsu.png
我想从我的可执行位置下的目录加载图像。
<ImageBrush x:Key="WindowBackground" ImageSource="./backgrounds/Zenitsu.png" Stretch="UniformToFill"/>
我曾尝试使用./backgrounds/or\backgrounds\但两者似乎都直接在项目中查找结果或在可执行文件的位置。
我的输出结构是这样的:
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 中引用图像资源?