Search code examples
c#wpfdata-bindingconvertersprism-5

WPF Binding to converter for an Image (Bitmap) not showing


I am having issues with an image not showing in a WPF control using a Converter to create the image from a local directory. Any direction on what I am doing wrong would be appreciated.

XAML

<UserControl x:Class="Coms.Views.ImageDetailView"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
         xmlns:c="clr-namespace:Coms.Converter"
         mc:Ignorable="d" 
         d:DesignHeight="100" d:DesignWidth="300" Background="Wheat">
<Control.Resources>
    <c:ImageDetailConverter x:Key="converter" />
</Control.Resources>
<ListBox ItemsSource="{Binding icList}" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition Width="100"/>
                    <ColumnDefinition Width="200"/>
                </Grid.ColumnDefinitions>
                <Image Name="imgBox" Width="auto" Height="auto" Grid.Column="0" Source="{Binding Converter={StaticResource converter}}" />
                <TextBlock Name="txtBlock2" Grid.Column="1" Text="{Binding coordinates}"/>
            </Grid>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

class

public class ImageDetail
{
    public string fileName { get; set; }
    public string coordinates { get; set; }
}

Converter

public class ImageDetailConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        IRuntimeConfigurations configs = ServiceLocator.Current.GetInstance<IRuntimeConfigurations>();
        return new Bitmap(Image.FromFile(Path.Combine(configs.rootImagePath, ((IImageDetail)value).fileName)));
    }
}

Solution

  • Your converter returns a System.Drawing.Bitmap, which is WinForms, not WPF.

    It should return a WPF ImageSource (e.g. a BitmapImage) instead:

    public object Convert(
        object value, Type targetType, object parameter, CultureInfo culture)
    {
        var imageDetail = (ImageDetail)value;
        var configs = ServiceLocator.Current.GetInstance<IRuntimeConfigurations>();
        var path = Path.Combine(configs.rootImagePath, imageDetail.fileName);
        var uri = new Uri(path, UriKind.RelativeOrAbsolute);
    
        return new BitmapImage(uri);
    }
    

    Note also that WPF provides built-in type conversion from Uri and string (containing a valid URI) to ImageSource, so that your converter could also return the uri or path value.