Can I set the base path outside of my application directory when binding an image source path to a relative path in WPF?
So I'm trying to display an image that is ouside the path of my applicati开发者_StackOverflowon. 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?
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}}"/>
精彩评论