views:

50

answers:

3

How do I proper case text as the user enters it in a WPF form. I'm using the following code to do the proper casing which works fine, but I can't figure out how to do it on user entry.

Microsoft.VisualBasic.Strings.StrConv(txt.Text,VbStrConv.ProperCase,0);
A: 
        TextInfo txtinfo = Thread.CurrentThread.CurrentCulture.TextInfo;
        string titleCaseString = txtinfo.ToTitleCase(theString);

To work this in the DataBinding, you can write a WPF Binding Converter and add this logic there.

        <TextBox>
         <TextBox.Text>
            <Binding Path="ViewModelProperty" Converter="{StaticResource TitleCaseConverter}" UpdateSourceTrigger="PropertyChanged" />
         </TextBox.Text>
       </TextBox>
Jobi Joy
A: 

You'll want to use code like you have, or Jobi posted, in the Key_Down (or Up) event of the text control.

Nate Bross
I don't think the KeyDown event will work because it fires before the key stroke has been added to the text property of the textbox. I need to take the entire string as an entity in order to work out which characters need to be upper cased. If I use the TextChanged event and I set the value of the text property to be the converted text value the cursor always goes to the front of the text string, so it means the user is effectively typing from right to left. Would appreciate any other suggestion you may have.
Mairead
I was just missing txt.Select(txt.Text.Length, 0);Thanks Nate Bross
Mairead
A: 

In our application we have a custom TextBox where we have overridden the PreviewTextInput event to perform validation there (we are validating the input against a regex and preventing the character from being added if it is invalid) - maybe you could do something similar?

I have had problems with custom TextBoxed before though, the caret jumping back to the start of the string was something I couldn't quite grasp either, can't remember how we got around it though.

TabbyCool