3
\$\begingroup\$

I am interested in hearing opinions on this. I need a way to dispose the old value of a property in a way that's compatible with BindableBase. Specifically, I have a few bound properties of type System.Drawing.Bitmap. Am I going about this all wrong?

using Prism.Mvvm;
using System;
using System.Runtime.CompilerServices;

namespace App.Infrastructure
{
    public class DisposableAwareBindableBase : BindableBase
    {
        /// <summary>
        /// Set a property, notifying property change listeners. If the property is of a type that implements IDisposable, Dispose() will be called on the old outgoing value if it is not null.
        /// </summary>
        /// <typeparam name="T">Type of property</typeparam>
        /// <param name="storage">Backing storage for property, passed by reference</param>
        /// <param name="value">New value of the property</param>
        /// <param name="propertyName">Property name</param>
        /// <returns>True if the property was set succesfully, false otherwise</returns>
        protected virtual bool SetAndDisposeProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
        {
            T old = storage;
            if (!SetProperty(ref storage, value, propertyName)) return false;
            if (old != null && old is IDisposable)
            {
                (old as IDisposable).Dispose();
            }
            return true;
        }
    }
}

Usage:

using App.Infrastructure;
using System.Drawing;

namespace App.UI
{
    internal class ConfigWindowViewModel : DisposableAwareBindableBase
    {

        // ...

        private Bitmap _PreviewImage;
        public Bitmap PreviewImage
        {
            get
            {
                return _PreviewImage;
            }
            set
            {
                SetAndDisposeProperty(ref _PreviewImage, value);
            }
        }

        // ...

    }
}

This class extends BindableBase from Prism Library.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.