【问题标题】:RichEditBox TextChangedEvent fired infinitely in UWP?RichEditBox TextChangedEvent 在 UWP 中无限触发?
【发布时间】:2020-10-13 16:54:30
【问题描述】:

我尝试了什么? 我的 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 中的文本时,如果我对更改 textCharacterFormat 的三行进行注释,则每次更改仅触发一次 textChangedEvent。如果取消注释这三行,则 textchanged 事件将无限触发。

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

【问题讨论】:

    标签: uwp uwp-xaml


    【解决方案1】:

    我不知道,为什么会发生这种情况以及如何更改 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的前景色。

    richbox.Document.Selection.CharacterFormat.ForegroundColor = Colors.Red;
    

    【讨论】:

    • 是的。会起作用。但是因为不断调用事件会影响应用程序的性能。有没有其他方法可以改变颜色?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 2020-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多