Aug 4, 2011

Brush object serialization and Isolated Storage

You probably already know that you cant serialize Brush objects using Isolated storage default serialization engine, so there are a few ways you can overcome this simple problem. There are a few approaches to solving this problem and some of them include serialization of brushes Argb byte values, or brush Color values. I'm gonna show you how to create a simple serializable class in order to overcome this problem by serializing brushes Color.

using System.Windows.Media;
using System.Runtime.Serialization;

namespace TheTime.Model
{
    [DataContract]
    public class BindableBrush
    {
        private string _brushName;
        /// <summary>
        /// Initializes a new instance of the BindableBrush class.
        /// </summary>
        public BindableBrush(Color c, string name)
        {
            Color = c;
            _brushName = name;
           
        }

        [DataMember]
        public Color Color
        { get; set; }


        public SolidColorBrush Brush 
        {
            get
            {
                return new SolidColorBrush(Color);
            }
            set
            {
                Color = value.Color;
            }
        }

        [DataMember]
        public string BrushName
        {
            get
            {
                return _brushName;
            }
            set
            {
                _brushName = value;
            }
        }
    }
}

This simple solution serializes the Color object and creates a SolidColorBrush on request. Using this class you can bind to the Brush property without any problem...

Hope it helps!

No comments: