我想在我的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;
}
}这段代码可以很好地显示图像,但我也应该能够更改图像运行时,也就是说,我想用另一个图像替换Icon.jpg。MyFolder是包含图像"Icon.jpg“的文件夹路径(名称将始终相同)。因此,每当我尝试用任何其他图像替换Icon.jpg时,我都会收到一个错误,即Image file in Use
有没有人能建议如何克服这个问题。如果我需要澄清我的问题,请告诉我。
感谢大家的期待。
发布于 2013-01-29 17:03:02
INotifyPropertyChanged。代码如下:
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 as按需加载能力。要将位图加载到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();
}https://stackoverflow.com/questions/14579059
复制相似问题