#635 – Using a Value Converter to Change User Input

Instead of modifying user input by handling the TextChanged event, you can use a value converter to change the text input.  Below, we bind the Text property of a TextBox to a string property and specify a converter, which will convert vowels to uppercase.

<Window x:Class="WpfApplication9.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WpfApplication9"
        Title="TextChanged"
        Height="150" Width="400">

    <Window.Resources>
        <ResourceDictionary>
            <local:CapVowelsConverter x:Key="capVowelsConverter"/>
        </ResourceDictionary>
    </Window.Resources>

    <StackPanel Orientation="Vertical">
        <TextBox HorizontalAlignment="Center" Width="150" Margin="10"
                 Text="{Binding Path=MyText, Converter={StaticResource capVowelsConverter}, UpdateSourceTrigger=PropertyChanged}"/>
        <Button Content="What Is My Text?" HorizontalAlignment="Center" Margin="10" Click="Button_Click"/>
    </StackPanel>
</Window>

Here’s the code for the value converter:

    public class CapVowelsConverter : IValueConverter
    {
        // From bound property TO the control -- no conversion
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            return value;
        }

        // To bound property FROM the control -- capitalize vowels
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            string input = (string)value;

            const string vowels = "aeiou";

            StringBuilder sbInput = new StringBuilder(input);
            for (int i = 0; i < sbInput.Length; i++)
            {
                if (vowels.Contains(char.ToLowerInvariant(sbInput[i])))
                    sbInput[i] = char.ToUpper(sbInput[i]);
            }

            return sbInput.ToString();
        }
    }


Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #635 – Using a Value Converter to Change User Input

  1. Pingback: Dew Drop – August 29, 2012 (#1,391) | Alvin Ashcraft's Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: