[英]how to stop text changed texbox from runing contains text code?
我将如何停止运行 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;
}
}
尽管有关于避免在事件处理程序中创建 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;
}
}
现在,此代码仅在添加新的 { } 对时才会触发。 每次添加 { } 对时,代码都会运行。 它不适合删除。 如果粘贴了包含多个 { } 的大量文本,则它不适合多个文本。因此它可能需要一些改进,但正如其他人所指出的那样,您没有告诉我们您要做什么,只是您的解决方案坏了,唉,解决方案并没有真正让我们推断出你想要做什么
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.