#635 – Using a Value Converter to Change User Input
August 29, 2012 1 Comment
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(); } }
Pingback: Dew Drop – August 29, 2012 (#1,391) | Alvin Ashcraft's Morning Dew