简体   繁体   中英

how to stop text changed texbox from runing contains text code?

How would I stop text changed from running if statement? because after I type {} the code runs, but if I type any letter or press enter after I type {} the code keeps on making new labels in every letter typed or entered. This is for WPF c#

            private void TextBox_TextChanged(object sender, EventArgs e)
            {            
                if (textBox.Text.Contains("{") && textBox.Text.Contains("}"))
                {             
                    DraggableLabel ag = new DraggableLabel();
                    ag.Name = "A";
                    ag.Content = "you have bracket";    //(i + 1).ToString();
                    ag.BorderBrush = Brushes.Black;
                    ag.BorderThickness = new Thickness(2, 2, 2, 2);
                    DesigningCanvas.Children.Add(ag);    

                    ab = ag;    
                }           
            }

Notwithstanding the comments about avoiding creating UI elements in event handlers, what you need is a system that only activates if there are new { } pairs in the textbox. Perhaps something like:

        private int brasProcessed = 0;

        private void TextBox_TextChanged(object sender, EventArgs e)
        {            
            int countOpenBra = textBox.Text.Count(c => c == '{');
            int countCloseBra = textBox.Text.Count(c => c == '}');

            //if there is a matched pair of {} (equal counts) and more { have appeared than we know we've processed before...
            if (countOpenBra == countCloseBra && countOpenBra > brasProcessed)
            {             
                DraggableLabel ag = new DraggableLabel();
                ag.Name = "A";
                ag.Content = "you have bracket";    //(i + 1).ToString();
                ag.BorderBrush = Brushes.Black;
                ag.BorderThickness = new Thickness(2, 2, 2, 2);
                DesigningCanvas.Children.Add(ag);    

                ab = ag;  

                //mark the current count of {} as processed so the code will not fire again until someone adds a new { } pair
                brasProcessed = countOpenBra;  
            }           
        }

Now this code will only fire when new pairs of { } are added. Every time you add a { } pair the code will run. It does not cater for deleted. It does not cater for multiples if a large amount of text containing multiple { } is pasted in. It hence likely needs some improvement but as others have noted you didn't tell us what you were trying to do, only that your solution for it was broken, and alas the solution didn't really allow us to infer what you're trying to do

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM