views:

345

answers:

3

I have an editable WPF ComboBox with TextSearchEnabled. I need to force the user's text input to uppercase when they type to filter the ComboBox.

I was thinking of modifying the textbox that is part of the control (named 'PART_EditableTextBox') to set CharacterCasing="Upper", however I can't quite figure out how to do this.

Do I need to use a trigger, or modify the template in some way?

+2  A: 

IMO, the quicker way is to set the UpdateTrigger to PropertyChanged and, in the data object, uppercase the value when it is updated.

kbok
A: 
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    Textbox editableTextbox = sender as Textbox;
    foreach (char ch in e.Text)
    {
        if (Char.IsLower(ch))
        {
            editableTextbox.Text += Char.ToUpper(ch);
            e.Handled = true;
        }
    }
}

or try creating an attached behaviour for the textbox

Veer
I believe this code will strip all upper-case characters out of the input.
Robert Rossney
@Robert Rossney: I don't think so. Only if the character is lower, it will be converted to uppercase and explicitly appended to the textbox and further handling is made false. If it is upper, then it is not handled at all.
Veer
Well, I'm not going to spoil the surprise for you, but you should test this. It doesn't do what I expected it to do, but it doesn't do what you expected it to do either. And the conclusion I've drawn from this exercise is that if you handle `PreviewTextInput`, you should expect to have to do a lot of testing and thinking to get the result to work the way you want.
Robert Rossney
@Robert Rossney: I don't have an IDE here. You may be right. I should test it. But if you've tested it, can you tell me what's going wrong here so that i would fix it. Else i would do that when i go home:)
Veer
Well, it's kind of hard to explain. There are a couple of issues, all having to do with the insertion point. The caret may not be at the end of the text, but that's where this always puts the character. So that's a problem. A more confusing problem is that handling `PreviewTextInput` not only keeps the character from being added to `Text` normally, it also keeps the caret from advancing normally. So if you put the caret in a `TextBox and type `abCd`, it will contain `CABD`, and the caret will be between the C and A.
Robert Rossney
I've just tested this approach and whilst it uppercases the characters, the insertion point remains at index zero, making it impossible for the user to press backspace to delete any characters.
Alex
+2  A: 

This works and seems like a reasonable solution:

protected void winSurveyScreen_Loaded(object sender, RoutedEventArgs e)
{
    (comboBox.Template.FindName("PART_EditableTextBox", cbObservation) as TextBox).CharacterCasing = CharacterCasing.Upper;
}

Ensure that the combobox is not collapsed on loaded otherwise the template will not be found.

Alex