简体   繁体   English

最适合model的bitmap class

[英]The most appropriate bitmap class for the model

I am writing a simple WPF application using MVVM.我正在使用 MVVM 编写一个简单的 WPF 应用程序。 What is the most convenient class to retrieve bitmaps from models and further data binding: Bitmap, BitmapImage, BitmapSource?模型中检索位图和进一步数据绑定最方便的 class 是什么:Bitmap、BitmapImage、BitmapSource?

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

Or maybe I can somehow convert Bitmap to BitmapSource using ViewModel?或者,也许我可以使用 ViewModel 以某种方式将 Bitmap 转换为 BitmapSource?

I always use BitmapImage , it's quite specialized and offers nice properties and events that might be useful (eg IsDownloading , DownloadProgress & DownloadCompleted ).我总是使用BitmapImage ,它非常专业,并提供了可能有用的好属性和事件(例如IsDownloadingDownloadProgressDownloadCompleted )。

I suppose the more flexible way is to return photo (or any other bitmap) as a stream.我想更灵活的方法是将照片(或任何其他位图)作为 stream 返回。 Furthermore, if the photo has been changed, the model should fire the photo changed event and the client should handle the photo changed event to retrieve a new one photo.此外,如果照片已更改,model 应触发照片更改事件,客户端应处理照片更改事件以检索新照片。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM