Thursday, November 13, 2014

Converters - Bool To Image convertor

Note: This is not my original work. Have blogged it here just for my future reference and of course if someone wants to use it.

This convertor is used to convert a Boolean value into an image. No need to say it is a very useful control provided by WPF.

Base class

public class BoolToImageConverter : IValueConverter
    {
        public BoolToImageConverter()
        {
           
        }

        public virtual object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if ((value.ToString() == "True" ||  value.ToString() == "1")? true : false)
                return "pack://application:,,,/myApplication
;component/Resources/Set.gif";
            else
                return "pack://application:,,,/
myApplication;component/Resources/UnSet.gif";
        }

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


Usage

 public BoolToImageConverter boolToImageConverter { get; set; }

boolToImageConverter = new BoolToImageConverter();

var flagImage = new FrameworkElementFactory(typeof(Image));
flagImage.SetBinding(Image.SourceProperty, new Binding(columnName) { Converter = boolToImageConverter });

No comments:

Post a Comment