我目前正在尝试在 WPF 项目中创建一些基本的文字处理功能。我正在使用 RichTextBox,并且知道所有的 EditingCommands(ToggleBold、ToggleItalic...等)。我所坚持的问题是允许用户更改字体大小和字体,就像在 MS Office 中一样,其中值仅针对选定的文本进行更改,如果没有选定的文本,则值将针对当前插入符号位置进行更改。我已经想出了相当多的代码来让它工作,但是我遇到了没有选择文本的问题。这是我为 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);
所以我的问题是我应该如何去做呢?有没有更好/更方便的方法来做到这一点?我的一个想法是我需要在段落中插入一个新的内联,但我不知道如何做到这一点。任何帮助表示赞赏。谢谢。
完整免责声明: 这是准确的转发this https://stackoverflow.com/questions/674384/wpf-richtextbox-fontface-fontsize7个月前的问题。我在寻找完全相同问题的解决方案时发现了它,但是这个问题没有得到解答,我希望有人现在能够回答它。
尝试这个:
private void ChangeTextProperty(DependencyProperty dp, string value)
{
if (mainRTB == null) return;
TextSelection ts = mainRTB.Selection;
if (ts.IsEmpty)
{
TextPointer caretPos = mainRTB.CaretPosition;
TextRange tr = new TextRange(caretPos, caretPos);
tr.Text = " ";
tr.ApplyPropertyValue(dp, value);
}
else
{
ts.ApplyPropertyValue(dp, value);
}
}
我希望它能起到作用
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)