【问题标题】:Can I set the base path outside of my application directory when binding an image source path to a relative path in WPF?将图像源路径绑定到 WPF 中的相对路径时,我可以在应用程序目录之外设置基本路径吗?
【发布时间】:2011-02-05 21:23:28
【问题描述】:

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

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

有没有什么方法可以在 XAML 中指定这些图像的基本目录或代码?

【问题讨论】:

    标签: c# wpf binding path relative-path


    【解决方案1】:

    在后面的代码中声明一个静态字段,例如 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}}"/>
    

    【讨论】:

    • 感谢您为我指出正确的方向。原来我需要在 Convert 方法中组合路径和相对路径,而不是 ConvertBack 方法。我仍在标记此权利,因为它解决了我的问题。我想我可能需要一个转换器,只是想可能有一个不同的解决方案......无论哪种方式......谢谢!
    • 这是因为我没有测试我的代码,无论如何,谢谢你指出我的错误,我已经更新了我的答案
    猜你喜欢
    • 2010-11-29
    • 2019-07-08
    • 2018-01-22
    • 1970-01-01
    • 2016-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 1970-01-01
    相关资源
    最近更新 更多