WPF图像动态绑定

时间:2013-01-29 09:00:31

标签: wpf image

我想在WPF窗口中显示图像。 我已经把这个代码这样做了。

<Image  x:Name="ImageControl" Stretch="Fill" Margin="2" Source="{Binding imgSource}"/>

在后面的代码中我已经放了,

    public ImageSource imgSource
    {
        get
        {
            logo = new BitmapImage();
            logo.BeginInit();
            logo.UriSource = new Uri(@"C:\MyFolder\Icon.jpg");
            logo.EndInit();                
            return logo;
        }
    }

此代码显示图像正常,但我也应该能够更改图像运行时,也就是说,我想用另一个Image替换Icon.jpg。 MyFolder是包含图像“Icon.jpg”的文件夹路径(名称将始终相同)。 因此,每当我尝试将Icon.jpg替换为任何其他图像时,我都会收到错误Image file in Use

任何人都可以建议如何克服这个问题。如果我需要澄清我的问题,请告诉我。

感谢Anticipation。

1 个答案:

答案 0 :(得分:1)

  • 在课堂上实施INotifyPropertyChanged

  • 将您的媒体资源更改为“获取”“设置”

  • 不要忘记设置DataContext。

以下是代码:

public class MyClass : INotifyPropertyChanged
{
    private string imagePath;
    public string ImagePath
    {
        get { return imagePath; }
        set
        {
            if (imagePath != value)
            {
                imagePath = value;
                BitmapImage bitmapImage = new BitmapImage();
                bitmapImage.BeginInit();
                bitmapImage.UriSource = new Uri(ImagePath);
                bitmapImage.EndInit();
                imgSource = bitmapImage;
            }
        }
    }

    public BitmapImage logo;
    public ImageSource imgSource
    {
        get { return logo; }
        set
        {
            if (logo != value)
            {
                logo = value;
                OnPropertyChanged("imgSource");
            }
        }
    }

    #region INotifyPropertyChanged implementation
    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
            handler(this, new PropertyChangedEventArgs(propertyName));
    }
    #endregion
}

更新

已知

BitmapImage在使用字符串传递路径时保持文件加载。 加载FileStream代替。 BitmapImage默认设置为按需加载功能。要使位图加载EndInit上的图片,您必须更改ChacheOption

using (FileStream stream = File.OpenRead(@"C:\MyFolder\Icon.jpg"))
{
    logo = new BitmapImage();
    logo.BeginInit();
    logo.StreamSource = stream;
    logo.CacheOption = BitmapCacheOption.OnLoad;
    logo.EndInit();
}
相关问题