首页 > 解决方案 > 如何阻止文本更改的 texbox 运行包含文本代码?

问题描述

我将如何停止运行 if 语句的文本更改?因为在我输入 {} 后代码运行,但如果我输入任何字母或在我输入 {} 后按 Enter 键,代码会继续在每个输入或输入的字母中制作新标签。这是针对 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;    
                }           
            }

标签: c#

解决方案


尽管有关于避免在事件处理程序中创建 UI 元素的评论,但您需要的是一个只有{ }在文本框中有新对时才会激活的系统。也许是这样的:

        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;  
            }           
        }

现在,此代码仅在添加新的 { } 对时才会触发。每次添加 { } 对时,代码都会运行。它不适合删除。如果粘贴了包含多个 { } 的大量文本,则它不适合多个文本。因此它可能需要一些改进,但正如其他人所指出的那样,您没有告诉我们您要做什么,只是您的解决方案坏了,唉,解决方案并没有真正让我们推断出你想要做什么


推荐阅读