最适合模型的位图类

本文关键字:位图 模型 | 更新日期: 2023-09-27 17:57:33

我正在使用MVVM编写一个简单的WPF应用程序。从模型和进一步的数据绑定中检索位图最方便的类是什么:位图、BitmapImage、BitmapSource?

public class Student
{
    public <type?> Photo
    {
        get;
    }
}

或者,我可以使用ViewModel以某种方式将位图转换为BitmapSource?

最适合模型的位图类

我总是使用BitmapImage,它非常专业,提供了可能有用的良好属性和事件(例如IsDownloadingDownloadProgressDownloadCompleted)。

我认为更灵活的方法是将照片(或任何其他位图)作为流返回。此外,如果照片已经更改,则模型应该触发照片更改事件,并且客户端应该处理照片更改事件以检索新的一张照片。

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