using System;
using System.Reflection;
using System.Windows;
using System.Windows.Data;
using System.Windows.Media;
using C1.Silverlight.DataGrid;
using C1.Silverlight.Imaging;

namespace C1DataGrid_Demo2010
{
    public class DataGridGifColumn 
        : DataGridBoundColumn
    {
        public DataGridGifColumn()
            : base()
        {
        }

        public DataGridGifColumn(PropertyInfo property)
            : base(property)
        {
        }

        public override object GetCellContentRecyclingKey(DataGridRow row)
        {
            return typeof(System.Windows.Controls.Image);
        }

        public override FrameworkElement CreateCellContent(DataGridRow row)
        {
            return new System.Windows.Controls.Image();
        }

        public override void BindCellContent(FrameworkElement cellContent, DataGridRow row)
        {
            var gif = (System.Windows.Controls.Image)cellContent;
            Binding binding = CopyBinding(Binding);
            binding.Converter = new GifConverter();
            binding.Source = row.DataItem;
            gif.SetBinding(System.Windows.Controls.Image.SourceProperty, binding);
        }
    }

    public class GifConverter : IValueConverter
    {

        #region IValueConverter Members

        public object Convert(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is string)
            {
                value = new Uri((string)value, UriKind.RelativeOrAbsolute);
            }
            if (value is Uri)
            {
                //The casting to an ImageSource object is required because it will be assigned to an Image control.
                return ((ImageSource)new C1GifImage((Uri)value));
            }
            return value;
        }

        public object ConvertBack(object value, System.Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }

        #endregion
    }
}
