none
Value Converter as Markup Extension RRS feed

  • General discussion

  • My first post on these blogs so bear with me! I recently did a project that relied heavily on ValueConverters and I would like to share a cool way of implementing it. Use MarkupExtensions! I find it easier to implemet on the XAML side.

    First of create your converter but inherit from MarkupExtension (System.Windows.Markup.MarkupExtension). Implement the IValueConverter interface and your good to go! The example I'm showing is a conversion from a nullable boolean dependency property on my viewmodel (IsValid) to a SolidColorBrush.

     

    Class Code:

        public class IsValidToBrushConverter : MarkupExtension, IValueConverter
        {
            public IsValidToBrushConverter() { }
            public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                SolidColorBrush source = null;
                if (value != null)
                {
                    if ((bool)value)
                    {
                        source = new SolidColorBrush(Colors.Green);
                    }
                    else
                    {
                        source = new SolidColorBrush(Colors.Red);
                    }
                }
                else
                {
                    source = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF042271"));
                }
                return source;
            }
    
            public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
            {
                throw new NotImplementedException();
            }
    
            public override object ProvideValue(IServiceProvider serviceProvider)
            {
                return this;
            }
        }
    

    Note the only funny business here is the ProvideValue method that needs to be overriden from the MarkupExtension inheritance. just return the instance of the class.

     

    The XAML part is just as easy. Add your namespace declaration to your XAML(in this case I called it local). It changes the Foreground property of the TextBlock dependant on the boolean value.

    <TextBlock Margin="1" Foreground="{Binding IsValid, Converter={local:IsValidToBrushConverter}}"
    

    I hope you finds this helpfull, I did!

    Tuesday, November 22, 2011 4:47 PM

All replies