WPF ComboBox, force input to UpperCase

2019-02-25 11:48发布

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?

4条回答
叛逆
2楼-- · 2019-02-25 12:28
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

查看更多
祖国的老花朵
3楼-- · 2019-02-25 12:31

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.

查看更多
ゆ 、 Hurt°
4楼-- · 2019-02-25 12:33

I found that post where the attached property is used. That permit to use that for all of your ComboBox without rewriting the code.

查看更多
\"骚年 ilove
5楼-- · 2019-02-25 12:41

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

查看更多
登录 后发表回答