开发者

WPF Richtextbox FontFace/FontSize

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.


Full disclaimer: This is an exact repost of this question from 7 months ago. I found it while searching for a solution to the exact same problem, however that question wasn't answered and I hope that someone will be able to answer it now nevertheless.


Try this:

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);
                }
            }

I hope it does the trick


You can either explicitly re-set the focus to the RichTextBox by calling its Focus() method after applying the new value to the TextRange, or better yet, make the toolbar items not focusable. for example, if you have a combobox for font sizes:

<ComboBox x:Name="FontSizeSelector" Focusable="False" />

Then you can just use the original code, without the need for calling Focus():

text.ApplyPropertyValue(RichTextBox.FontSizeProperty, value);


OK, just found the answer:

 private void ChangeTextProperty(DependencyProperty dp, string value)
    {
        if (mainRTB == null) return;

        TextSelection ts = richTextBox.Selection;
        if (ts!=null)
            ts.ApplyPropertyValue(dp, value);
        richTextBox.Focus();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜