将图像源路径绑定到 WPF 中的相对路径时,是否可以在应用程序目录之外设置基本路径?

发布于 2024-08-28 08:30:10 字数 311 浏览 1 评论 0原文

所以我试图显示一个在我的应用程序路径之外的图像。我只有一个相对图像路径,例如“images/background.png”,但我的图像位于其他位置,我可能想在运行时选择该基本位置,以便绑定映射到正确的文件夹。例如“e:\data\images\background.png”或“e:\data\theme\images\background.png”

<Image Source="{Binding Path=ImagePathWithRelativePath}"/>

有没有办法在 XAML 或代码后面指定这些图像的基本目录?

So I'm trying to display an image that is ouside the path of my application. I only have a relative image path such as "images/background.png" but my images are somewhere else, I might want to choose that base location at runtime so that the binding maps to the proper folder. Such as "e:\data\images\background.png" or "e:\data\theme\images\background.png"

<Image Source="{Binding Path=ImagePathWithRelativePath}"/>

Is there any way to specify either in XAML or code behind a base directory for those images?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

死开点丶别碍眼 2024-09-04 08:30:10

在代码后面声明一个静态字段 BasePath

class Utility
{
    public static BasePath;
}

为其指定要用作基本路径的路径

声明一个转换器,如下所示:

public class RelativePathToAbsolutePathConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //conbine the value with base path and return
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // return whatever you want
    }
}

更新您的绑定以使用转换器

<Window.Resources>
<local:RelativePathToAbsolutePathConverter x:Key="RelativePathToAbsolutePathConverter"/>
</Window.Resources>

<Image Source="{Binding Path=ImagePathWithRelativePath, Converter={StaticResource RelativePathToAbsolutePathConverter}}"/>

Declare a static field say BasePath in code behind

class Utility
{
    public static BasePath;
}

assign it the path that you want to use as base path

declare a converter like this:

public class RelativePathToAbsolutePathConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        //conbine the value with base path and return
    }

    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // return whatever you want
    }
}

Update your binding to use a converter

<Window.Resources>
<local:RelativePathToAbsolutePathConverter x:Key="RelativePathToAbsolutePathConverter"/>
</Window.Resources>

<Image Source="{Binding Path=ImagePathWithRelativePath, Converter={StaticResource RelativePathToAbsolutePathConverter}}"/>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文