您可以创建一个转换器,例如:
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 中引用图像资源?