WPF 绑定到转换器的图像(位图)未显示

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

我在使用转换器从本地目录创建图像时遇到图像未显示在 WPF 控件中的问题。任何关于我做错事的指示都将不胜感激。

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; }
}

转换器

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)));
    }
}

您的转换器 return 是 System.Drawing.Bitmap,它是 WinForms,而不是 WPF。

它应该 return WPF ImageSource(例如 BitmapImage)而不是:

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);
}

另请注意,WPF 提供了从 Uristring(包含有效 URI)到 ImageSource 的内置类型转换,因此您的转换器也可以 return uripath 值。