Search code examples
c#windows-phone-7windows-phone-8windows-phone

TextBox only in uppercase


I want the TextBox only be in uppercase. in windows phone it doesn't has CharacterCasing, only solution I can think of is:

private void textBox_TextChanged(object sender, TextChangedEventArgs e)
{
   textBox.Text = textBox.Text.ToUpper();
}

It will do the process each time user presses a key which is not good. Is there a better way?


Solution

  • Unfortunately, there is no better way than tracking TextChanged. However, your implementation is flawed because it doesn't account for the fact that the user might change the caret position.

    Instead, you should use this:

    private void TextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
    {
        TextBox currentContainer = ((TextBox)sender);
        int caretPosition = currentContainer.SelectionStart;
    
        currentContainer.Text = currentContainer.Text.ToUpper();
        currentContainer.SelectionStart = caretPosition++;
    }