首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >RichEditBox TextChangedEvent在UWP中无限地开火?

RichEditBox TextChangedEvent在UWP中无限地开火?
EN

Stack Overflow用户
提问于 2020-10-13 07:57:02
回答 1查看 44关注 0票数 0

我试过什么?我的Xmal密码:

代码语言:javascript
复制
<Grid x:Name="grid">
     <RichEditBox x:Name="richbox" TextChanged="RichEditBox_TextChanged" Width="300" Height="70"/>
</Grid>

我的C#代码:

代码语言:javascript
复制
    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.If的三行--取消注释的三行--则textchanged事件将无限触发。

我不知道,为什么会发生这种情况,我如何在uwp中更改TextCharacterFormat ForegroundColor?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-13 08:39:13

我不知道,为什么会发生这种情况,我如何在uwp中改变TextCharacterFormat ForegroundColor?

问题是SetDefaultCharacterFormat方法将触发TextChanged,并且将SetDefaultCharacterFormat放置在TextChanged事件中,它将使事件变成无限循环。

对于您的方案,您可以创建一个值来记录以前的值。如果当前值与以前的值不同,则调用SetDefaultCharacterFormat可以防止无限循环。

代码语言:javascript
复制
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。

代码语言:javascript
复制
richbox.Document.Selection.CharacterFormat.ForegroundColor = Colors.Red;
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64330983

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档