在我的类中绑定图像控件到BitmapImage

本文关键字:控件 BitmapImage 图像 绑定 我的 | 更新日期: 2023-09-27 18:16:43

每当我想要显示过去的图像时,我都会将图像路径绑定到图像的源属性。太容易了。

现在我想改变图像,总是显示图像最新的变化。更改图像保存在类中的BitmapImage属性中。因此,不是要求图像控件从光盘加载图像,我想将其直接绑定到我的BitmapImage属性。但是图像没有显示。

然后(只是为了测试)我创建了一个值转换器,使用路径的图像在那里创建一个BitmapImage,并返回到控制-和图像显示。

再次说明:从转换器内部的路径创建BitmapImage有效。用相同的代码将图像控件绑定到在我的类中创建的BitmapImage属性失败。

描述了同样的问题,但"解决方案"不起作用。(我想知道为什么它被标记为解决,因为OP做出了相同的评论)

https://stackoverflow.com//questions/7263509/directly-binding-a-bitmapimage-created-inside-a-class-bound-to-a-listbox-in-wpf

编辑:这里是一些代码

这是成功创建可见图像的转换器。

public class BsConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        BitmapImage bi = new BitmapImage(new Uri(value.ToString()));
        return bi;
    }
    public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

…以及显示图像的XAML绑定。FileFileInfo类型,FullName为完整路径。

<Image MinHeight="100" MinWidth="100" Source="{Binding SelectedImage.File.FullName, Converter={StaticResource BsConverter}}"/>

我有一个属性BitmapImage image { get; set; },我在类的构造函数中初始化:

image = new BitmapImage();
image.BeginInit();
image.UriSource = new Uri(file.FullName);
image.CacheOption = BitmapCacheOption.OnLoad;
image.EndInit();

…还有绑定。但是——没有快乐。不显示图片

<Image MinHeight="100" MinWidth="100" Source="{Binding SelectedImage.image}"/>

在我的类中绑定图像控件到BitmapImage

该属性必须是公共的。为了更新绑定,定义属性的类必须实现INotifyPropertyChanged接口。

public class SelectedImage : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private ImageSource image;
    public ImageSource Image
    {
        get { return image; }
        set
        {
            image = value;
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("Image"));
            }
        }
    }
}

我遇到了同样的问题,这似乎与图片的定时和异步加载有关。可能转换器代码在Dispatcher中以不同的优先级运行,所以它的行为不同。

对于我的项目,我通过在代码中显式预加载BitmapImage来解决此行为,如

        Dim result As ScaleItImageSource = Nothing
    Dim stream As System.IO.FileStream = Nothing
    Try
        stream = New System.IO.FileStream(fileName, IO.FileMode.Open, IO.FileAccess.Read)
        Dim decoder As BitmapDecoder = System.Windows.Media.Imaging.BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.OnLoad)
        If decoder.Frames.Count > 0 Then
            result = New ScaleItImageSource(decoder.Frames(0), fileName)
        End If
    Finally
        If stream IsNot Nothing Then
            stream.Close()
        End If
    End Try
    Return result