如何在WPF RichTextBox中更改FontFamily,而不修改以前的文本 [英] How can I change the FontFamily in a WPF RichTextBox without modifying previous text

查看:168
本文介绍了如何在WPF RichTextBox中更改FontFamily,而不修改以前的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您使用RichTextBox的FontFamily属性时,它将更改FlowDocument中整个内容的FontFamily. 您可以执行类似EditingCommands.ToggleBold这样的命令的方式,在该命令中,它仅更改插入符号下的单词或仅更改要写入的新文本,应该有一种方法可以对FontsFamilies和Color进行相同的操作.

When you use the FontFamily property of the RichTextBox it changes the FontFamily of the whole content inside the FlowDocument. The same way you can Execute a command like EditingCommands.ToggleBold, where it only changes the word under the caret or just the new text to be written, there should be a way to do the same thing with the FontsFamilies, and Color.

推荐答案

也许不是最简洁的解决方案,但是您可以从RichTextBox继承并添加一些行为

Maybe not the neatest solution but the you can inherit from the RichTextBox and add some behavior

声明自己的字体属性,以便以后可以将它们与字体列表绑定

Declare your own Font Properties so you can bind them later with a List of Fonts

    public class CustomControl1 : RichTextBox
    {

public static readonly DependencyProperty CurrentFontFamilyProperty =
                DependencyProperty.Register("CurrentFontFamily", typeof(FontFamily), typeof  (CustomControl1), new FrameworkPropertyMetadata(new FontFamily("Tahoma"), FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,new PropertyChangedCallback(OnCurrentFontChanged)));
    }

重写OnTextInput.您无法在RichTextBox具有内置处理KeyDown和KeyUp气泡的功能上订阅此事件,并且在它们之间生成TextInput

Override the OnTextInput. You can't subscribe to this event on the RichTextBox has built-in handling for the bubbling of KeyDown and KeyUp and between them the TextInput is generated

    protected override void OnTextInput(TextCompositionEventArgs e)
{
        if (fontchanged)
        {
            TextPointer tp = this.CaretPosition.GetInsertionPosition(LogicalDirection.Forward);
            Run r = new Run(e.Text, tp);
            r.FontFamily = CurrentFontFamily;
            r.Foreground = CurrentForeground;
            this.CaretPosition = r.ElementEnd;
            fontchanged = false;
        }
        else
            base.OnTextInput(e);
    }

如果您的CurrentFontProperty已更改,请获得插入符号的位置,并使用新的文本输入创建一个新的运行,并设置FontFamily = CurrentFontFamily.您也可以更改整个单词,如果字词在某个单词的上方,则这篇文章可能很有趣,可以发现

if your CurrentFontProperty has changed get the caret position and create a new Run with the new Text Input and set the FontFamily = CurrentFontFamily. You could also change the whole word if the carret is over a word, this article might be interesting to spot the word Navigate Words in RichTextBox.

这篇关于如何在WPF RichTextBox中更改FontFamily,而不修改以前的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆