Visual Studio 2010 and .NET 4.0 - Useful links

by Victor 31. December 2011 01:04

Using WPF Value Converters

by Wesley 3. December 2011 01:45

Sometimes you're binding information that you want to reformat before it's displayed to the user or you want to format a multibinding. The easiest solution is a Value Converter.

[ValueConversion(typeof(object), typeof(object))] 
public class MyValueConverter: IValueConverter 
{ 
     public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
     {        
          return null;     
     } 

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


The ValueConversion attribute requires the input type followed by the output type. If the value converter is only being used only one-way for displaying data, the ConvertBack method can be left as null. Here's an example of a Converter that displays a boolean as "Yes" or "No"

    [ValueConversion(typeof(bool), typeof(string))]
    public class BoolToStringConverter: IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            bool input = (bool)value;

            if (input)
                return "Yes";
            else
                return "No";
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;

            string input = (string)value;

            if (input == "Yes")
                return true;
            else
                return false;
        }
    }

And then our xaml contains:

<UserControl xmlns:c="clr-namespace:Converters" >

    <UserControl.Resources>
        <c:BoolToStringConverter x:Key="BoolToStringConverter" />
    </UserControl.Resources>

    <TextBox Text="{Binding Path=MyBool, Converter={StaticResource BoolToStringConverter}}" />
</UserControl>

IMultiValueConverters work the same as IValueConverters. Convert takes in an array of values and outputs one value and ConvertBack takes one value and returns an array. There is one very important thing to remember with IMultiValueConverters. A value in the values array will never be null. the array is populated with as many rows as bindings. If a binding is null, the object will be given a string value as shown below.

[ValueConversion(typeof(object), typeof(object))]
    public class MyMultiConverter: IMultiValueConverter
    {
  
        public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
        {          
           foreach (object val in values)
                if (val.ToString() == "{DependencyProperty.UnsetValue}")
                    return null;
        }

        public object[] ConvertBack(object value, Type[] targetType, object parameter, CultureInfo culture)
        {
            if (value == null)
                return null;
        }
    }

And then the xaml for a multibinding:

<TextBox>
        <TextBox.Text>
            <MultiBinding Converter="{StaticResource MyMultiConverter}">
                <Binding Path="Info1" />
                <Binding Path="Info2" />
            </MultiBinding>
        </TextBox.Text>
    </TextBox>

Also, if you're using a converter for a control that displays multiple items, it is important to remember that the SelectedValue property will be in the same format as the output. If you want to bind the control's SelectedValue, it will need the same converter as the ItemsSource to convert back to the correct format.

Finally, If all you want to do is basic text formatting, you can use StringFormat instead of a Converter. It allows for all the same formatting you can do with String.Format.

<TextBox>
        <TextBox.Text>
            <MultiBinding StringFormat="{} Info1: {0}, Info2: {1}">
                <Binding Path="Info1" />
                <Binding Path="Info2" />
            </MultiBinding>
        </TextBox.Text>
    </TextBox>



Tags: , ,

Powered by BlogEngine.NET 2.5.0.6

About Us

Wuji Touch is a software consulting firm based in Delray Beach, Florida. We specialize in Microsoft technologies, but we also have experience with Progress OpenEdge, iOS, and Android development. This is our blog. These are the tales of the pains and pleasures we experience daily in our journey through 1s and 0s.

Month List