我正在使用MVVM编写一个简单的WPF应用程序。 从模型检索位图和进一步数据绑定最方便的类是什么:Bitmap,BitmapImage,BitmapSource?
public class Student
{
public <type?> Photo
{
get;
}
}
或许我可以用ViewModel以某种方式将Bitmap转换为BitmapSource?
答案 0 :(得分:1)
我总是使用BitmapImage
,它非常专业,并提供可能有用的不错属性和事件(例如IsDownloading
,DownloadProgress
&amp; DownloadCompleted
)。
答案 1 :(得分:0)
我认为更灵活的方法是将照片(或任何其他位图)作为流返回。 此外,如果照片已更改,模型应触发照片更改事件,客户端应处理照片更改事件以检索新照片。
public class PhotoChangedEventArgs : EventArgs
{
}
public class Student
{
public Stream GetPhoto()
{
// Implementation.
}
public event EventHandler<PhotoChangedEventArgs> OnPhotoChanged;
}
public class StudentViewModel : ViewModelBase
{
// INPC has skipped for clarity.
public Student Model
{
get;
private set;
}
public BitmapSource Photo
{
get
{
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = Model.Photo;
image.EndInit();
image.Freeze();
return image;
}
}
public StudentViewModel(Student student)
{
Model = student;
// Set event handler for OnPhotoChanged event.
Model.OnPhotoChanged += HandlePhotoChange;
}
void HandlePhotoChange(object sender, PhotoChangedEventArgs e)
{
// Force data binding to refresh photo.
RaisePropertyChanged("Photo");
}
}