c# - 如何阻止文本更改的 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;
}
}
解决方案
尽管有关于避免在事件处理程序中创建 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;
}
}
现在,此代码仅在添加新的 { } 对时才会触发。每次添加 { } 对时,代码都会运行。它不适合删除。如果粘贴了包含多个 { } 的大量文本,则它不适合多个文本。因此它可能需要一些改进,但正如其他人所指出的那样,您没有告诉我们您要做什么,只是您的解决方案坏了,唉,解决方案并没有真正让我们推断出你想要做什么
推荐阅读
- php - Laravel Wherehas 在枢轴关系中不起作用并且不返回任何数据
- docker - SSH 到 Kubernetes 中的 Sshd docker 服务器会随机返回 exitCode=255
- html - 我想显示我从下拉列表中选择的城市天气信息,我该如何管理它?
- java - Thymeleaf 中的可选参数?
- c# - 什么时候应该使用列表而不是 ICollection 或 IEnumerable?
- android - 如何使用 Kotlin 为 RecyclerView 创建上下文菜单
- phing - Ubuntu 上 phing.php 的权限,以便在 Eclipse 中执行
- vba - 如何将访问表传输到 CSV 文件?
- typo3 - 检查带有错字链接的链接页面是否隐藏
- mysql - 避免在查询中重复并将所有重复的行留空