开发者

The most appropriate bitmap class for the model

I am writing a simple WPF application using MVVM. What is the most convenient class to retrieve bitmaps from models and further data binding: Bitmap, BitmapImage, BitmapSource开发者_开发知识库?

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

Or maybe I can somehow convert Bitmap to BitmapSource using ViewModel?


I always use BitmapImage, it's quite specialized and offers nice properties and events that might be useful (e.g. IsDownloading, DownloadProgress & DownloadCompleted).


I suppose the more flexible way is to return photo (or any other bitmap) as a 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.

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜