WPF的RichTextBox FontFace /字号 [英] WPF Richtextbox FontFace/FontSize

查看:387
本文介绍了WPF的RichTextBox FontFace /字号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在在WPF项目中创建一些基本的文字处理功能。我使用一个RichTextBox和我知道所有的EditingCommands的(ToggleBold,ToggleItalic ...等)。我被困在事情是允许用户在微软Office改变字体大小和字体的脸像,其中只有选定的文本,如果没有选定文本则该值将当前插入符位置改变数值的变化。
我想出了一个代码像样的量得到这个工作,但我有与没有选定文本的东西的问题。 。这是我在做什么的RichTextBox.Selection

I am currently trying to create some basic word processor features in a WPF project. I am using a RichTextBox and am aware of all of the EditingCommands (ToggleBold, ToggleItalic...ect.). The thing I am stuck on is allowing the user to change the fontsize and font face like in MS Office where the value changes for only the selected text and if there is no selected text then the value will change for the current caret position. I have come up with a decent amount of code to get this to work, but am having problems with the no selected text thing. Here is what I am doing for the RichTextBox.Selection.

TextSelection text = richTextBox.Selection;
if (text.IsEmpty)
{
    //doing this will change the entire word that the current caret position
    //is on which is not the desire/expected result.
    text.ApplyPropertyValue(RichTextBox.FontSizeProperty, value);
}
else
    //This works as expected.
    text.ApplyPropertyValue(RichTextBox.FontSizeProperty, value);



所以我的问题是我应该如何去这样做?有没有更好/更便捷的方式做到这一点?
我想过了,我需要插入一个新的内联成段落,但我无法弄清楚如何做到这一点。任何帮助表示赞赏。谢谢你。

So my question is how should I go about doing this? Is there a better/more convenient way to do this? One thought I had was that I would need to insert a new Inline into the Paragraph but I couldn't figure out how to do that. Any help is appreciated. Thank you.

推荐答案

@子JP是正确的,你需要将焦点设置回 RichTextBox的,否则你会改变一个选择的属性,但是当您单击后退到文本框中,你会得到与现有的字体的新的选择。试着改变你的代码是这样的:

@sub-jp is right, you need to set the focus back to the RichTextBox, otherwise you'll change the properties of one selection, but when you click back to the text box, you'll get a new selection with the existing font. Try changing your code to be like this:

TextSelection text = richTextBox.Selection;

richTextBox.Focus();

text.ApplyPropertyValue(RichTextBox.FontSizeProperty, value);



...然后它应该正常工作既当有高亮显示文本,并在没有

...and then it should work correctly both when there is text highlighted, and when there is not.

另外,由于这里建议,可以设置可聚焦 ComboBox的属性,以避免此问题完全。

Alternatively, as suggested here, you can set the Focusable property of the ComboBox to False, to avoid this issue entirely.

这篇关于WPF的RichTextBox FontFace /字号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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