如何解决RichEditBox TextChangedEvent在UWP中无限触发?
我尝试了什么? 我的Xmal代码:
<Grid x:Name="grid">
<RichEditBox x:Name="richbox" TextChanged="RichEditBox_TextChanged" Width="300" Height="70"/>
</Grid>
我的C#代码:
static int count = 0;
private void RichEditBox_TextChanged(object sender,RoutedEventArgs e)
{
RichEditBox richEditBox=sender as RichEditBox;
Debug.WriteLine("Count : " + count++);
// ITextCharacterFormat textCharacterFormat = richEditBox.Document.GetDefaultCharacterFormat();
// textCharacterFormat.ForegroundColor = Colors.Blue;
// richEditBox.Document.SetDefaultCharacterFormat(textCharacterFormat);
}
当我尝试更改RichEditBox中的文本时,每次更改仅触发一次textChangedEvent,如果我注释了更改textCharacterFormat的三行。如果取消注释三行,则textchanged事件无限触发。
我不知道,为什么会这样,如何更改uwp中的TextCharacterFormat ForegroundColor?
解决方法
我不知道,为什么会这样,如何更改uwp中的TextCharacterFormat ForegroundColor?
问题是SetDefaultCharacterFormat
方法将触发TextChanged
,并将SetDefaultCharacterFormat
放置在TextChanged
事件中,它将使事件陷入无限循环。
对于您的方案,您可以输入一个值来记录先前的值。如果当前值与以前的值不同,则调用SetDefaultCharacterFormat
来防止无限循环。
static int count = 0;
private string prevoius = string.Empty;
private void RichEditBox_TextChanged(object sender,RoutedEventArgs e)
{
RichEditBox richEditBox = sender as RichEditBox;
Debug.WriteLine("Count : " + count++);
var current = string.Empty;
richEditBox.Document.GetText(TextGetOptions.FormatRtf,out current);
if (current.Length != prevoius.Length)
{
ITextCharacterFormat textCharacterFormat = richEditBox.Document.GetDefaultCharacterFormat();
textCharacterFormat.ForegroundColor = Colors.Blue;
richEditBox.Document.SetDefaultCharacterFormat(textCharacterFormat);
}
prevoius = current;
}
更新
还有其他改变颜色的方法
您可以创建特定的颜色按钮,然后调用以下代码来编辑Richbox的ForegroundColor。
richbox.Document.Selection.CharacterFormat.ForegroundColor = Colors.Red;
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。