How do I bind a WPF Image element to a PNG on the local hard drive using a relative filepath derived from a DB?

孤者浪人 提交于 2019-12-04 11:34:30
Athari

You need to use custom value converter to convert strings to images if you want to load files from the file system. Image.Source, when a string is passed, expects a file name from resources. You can find implementation of a such converter here: Display an image in WPF without holding the file open.

Thank you Athari, you got me on the right path!

Revised chunk of XAML...

<Window x:Class="pf_sharecalc.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Share Calculator" WindowStyle="ThreeDBorderWindow" Loaded="Window_Loaded"
    xmlns:local="clr-namespace:pf_sharecalc">

<Window.Resources>
    <local:PathToImageConverter x:Key="PathToIMageConverter"/>
    <DataTemplate x:Key="assetLBTemplate">
        <StackPanel Orientation="Horizontal">
            <Image Height="32" Width="32" Source="{Binding imageFileName, Converter={StaticResource PathToIMageConverter}}" />
            <TextBlock Text="{Binding imageFileName}" />
            <TextBlock Text="{Binding assetName}" />
        </StackPanel>
    </DataTemplate>
</Window.Resources>

And I added this code...

public class PathToImageConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        string path = value as string;
        if (path != null)
        {
            BitmapImage image = new BitmapImage();
            using (FileStream stream = File.OpenRead(path))
            {
                image.BeginInit();
                image.StreamSource = stream;
                image.CacheOption = BitmapCacheOption.OnLoad;
                image.EndInit(); // load the image from the stream
            } // close the stream
            return image;
        }
        else
            return null;
    }
    public object ConvertBack(object value, Type targetType,
                              object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

I'll have to do some fine tuning to get exactly what I want, but I've passed the road-block.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!