c# - How do I set a property to the last typed symbol in richtextbox in wpf?
问题描述
I want to set some background or foreground properties to the latest symbol in RichTextBox.
I tried getting the latest textrange by saving the caret position before the input and then getting the textrange like that: new TextRange(previousCaret, currentCaret)
.
However this is a bug-prone decision, because you can actually get 2 or more last symbols in case if the caret position wasn't updated in time (for example, you are typing very quickly and pressing the buttons at the same time)
Now, maybe I don't even have to get the latest symbol's TextRange? Are there other ways, like some built-in methods?
So, how do I change the latest symbol's properties properly?
解决方案
要获取最新的 TextRange,只需使用以下代码:
private TextRange LatestSymbol
{
get
{
var previous = InputString.CaretPosition.GetPositionAtOffset(-1);
if (previous != null)
{
return new TextRange(
previous,
InputString.CaretPosition
);
}
return null;
}
}
}
这里的问题是, CaretPosition.GetPositionAtOffset(-1) 返回当前位置后面 1 个符号的位置。
这很好用,没有任何错误。
推荐阅读
- ios - 无法单击自定义 UICollectionViewCell 内容
- node.js - 使用 multer 发送状态和文件
- tensorflow - Tensorflow - 训练亚当
- c - 什么是形式参数中的默认存储类
- azure - 如何在 VSTS 中部署 azure 函数应用代码和 ARM 模板
- r - 什么是 dplyr rowwise() 的 Plyr 版本
- azure - 如何使用 Terraform 将 VM 添加到 Azure 中的负载均衡器?
- sql - 我不知道如何创建这个 sql 查询
- php - 格式化 PHP 数组以生成 JSON 数组,而不是对象
- mysql - 按列 id 选择行,如果为 null,则包括包含另一列中相同值的行