Home > OS >  How to lower case automatically lower case the 2nd letter of every Word in a WPF Textbox?
How to lower case automatically lower case the 2nd letter of every Word in a WPF Textbox?

Time:07-21

I am trying to automatically set the 2nd letter of every Word into lower case. My Code is already working but i have one problem. Only the first word of the textbox is being converted if the 2nd letter isn't written in lower case. The rest of the textbox is just being ignored. Thank you in advance!

public MainWindow()
        {
            InitializeComponent();
        }

        private void Text1_KeyUp(object sender, KeyEventArgs e)
        {
            string erg;
            string input;
            input = Text1.Text;
            
            if (input.Length > 1  && input != "MW" && input !="HS" && input != "GR" )
            {
                var temp=Text1.GetLineLength;
                erg = input[0]   input.Substring(1, 1).ToLower()   input[2..];
                Text1.Text = erg;
                Text1.CaretIndex = Text1.CaretIndex   temp;
            } 

CodePudding user response:

Here is a quick little snippet of code which should do the thing you've wanted. But i would advice you to use TextChanged instead of KeyUp which amongst other things would make using shortcuts as ctrl a possible.

        public MainWindow()
        {
            InitializeComponent();
        }

        private void Text1_TextChanged(object sender, TextChangedEventArgs e)
        {
            string input = Text1.Text;
            string result = string.Empty;

            var caretIndex = Text1.CaretIndex;

            if (input.Length > 1 && input != "MW" && input != "HS" && input != "GR")
            {
                result  = input[0];

                bool spaceEncountered = true;

                for (int i = 1; i < input.Length; i  )
                {
                    if (input[i] == ' ')
                    {
                        result  = input[i];
                        spaceEncountered = true;
                    }
                    else
                    {
                        if (spaceEncountered && char.IsLetter(input[i - 1]))
                        {
                            result  = $"{input[i]}".ToLowerInvariant();
                            spaceEncountered = false;
                        }
                        else
                        {
                            result  = input[i];
                        }
                    }
                }

                Text1.Text = result;
                Text1.CaretIndex = caretIndex;
            }
        }
  • Related