目前,我正试图在WPF项目中创建一些基本的字处理器功能。我正在使用RichTextBox,并且知道所有的EditingCommands (ToggleBold,ToggleItalic...ect.)。我坚持要做的是允许用户更改字体大小和字体面,就像在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);所以我的问题是我该怎么做呢?有没有更好/更方便的方法来做这件事?有一个想法是,我需要在段落中插入一个新的行文,但我想不出如何做到这一点。任何帮助都是非常感谢的。谢谢。
完全免责声明:这是7个月前this问题的确切转贴。我在寻找一个完全相同的问题的解决方案时发现了这个问题,但是这个问题没有得到回答,我希望现在有人能够回答这个问题。
发布于 2009-10-19 13:13:29
好吧,找到答案了:
private void ChangeTextProperty(DependencyProperty dp, string value)
{
if (mainRTB == null) return;
TextSelection ts = richTextBox.Selection;
if (ts!=null)
ts.ApplyPropertyValue(dp, value);
richTextBox.Focus();
}发布于 2009-10-19 08:06:18
试试这个:
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);
}
}我希望它能起作用
发布于 2010-06-15 21:32:54
您可以在将新值应用到RichTextBox之后,通过调用其Focus()方法显式地重新设置焦点到TextRange,或者更好的是,使工具栏项不可聚焦。例如,如果您有一个字体大小的组合框:
<ComboBox x:Name="FontSizeSelector" Focusable="False" />然后您可以只使用原始代码,而不需要调用Focus():
text.ApplyPropertyValue(RichTextBox.FontSizeProperty, value);https://stackoverflow.com/questions/1587309
复制相似问题