我试过什么?我的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.If的三行--取消注释的三行--则textchanged事件将无限触发。
我不知道,为什么会发生这种情况,我如何在uwp中更改TextCharacterFormat ForegroundColor?
发布于 2020-10-13 08:39:13
我不知道,为什么会发生这种情况,我如何在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;https://stackoverflow.com/questions/64330983
复制相似问题