Formatting specifc lines of text in WPF RichTextBox - wpf

In a WPF .NET 4.0 RichTextBox with the following text:
Apple
Cheese
Orange
Pear
Chicken
How would I programmatically with C#, (not with XAML markup), bold all lines that start with the character "C"?
More generally, how do you get a reference to a given line of text from a RichTextBox and then apply some formatting to it?

Well that was trickier than I expected but I think the code below does it:
foreach (var paragraph in richTextBox1.Document.Blocks)
{
var text = new TextRange(paragraph.ContentStart,
paragraph.ContentEnd).Text;
paragraph.FontWeight = text.StartsWith("C") ?
FontWeights.Bold : FontWeights.Normal;
}
Basically, the RichTextBox holds its content in a FlowDocument (accessed through the Document property), which in turn has a collection of Blocks containing each Paragraph. Actually, each item in the Blocks collection can be anything derived from the abstract class Block...but I'm assuming if you only ever add simple text to your RichTextBox then they'll always just be Paragraphs. See here for a better explanation!
The trickiest part is that to get the text out of the paragraph you need to use the TextRange class...but the good news is that, once we have the text, the Paragraph has simple properties on it for setting the font weight, etc!

Related

Write text with bullets and numbering WPF

I need to insert into a border text with bullets (look at the next picture for example):
Is there any special property for this or should I use some container like grid and get this manually?
If your solution rely on Expression Blend it fine by me (I`m using Blend 4).
Thanks
Ofir

RichTextBox SelectionFont is unexpectedly *not* null

I'd like to change the font size of a chunk of RTF without erasing the bold / italic / underline formatting (an issue similar to the one in this question). The accepted answer is to modify the selection of the text box until the SelectionFont propery is null in order to find runs of consistently formatted text which can be modified individually. Sounds reasonable. However the actual behavior of the RichTextBox control seems to be inconsistent with the documentation.
In the documentation for RichTextBox.SelectionFont MSDN states:
If the current text selection has more than one font specified, this
property is null.
However, this code which uses mixed bold / regular text doesn't behave as you'd expect:
var rtb = new RichTextBox {
Rtf = #"{\rtf1 This is \b bold\b0.}"
};
rtb.SelectAll();
// Now you'd expect rtb.SelectionFont to be null,
// but it actually returns a Font object
Is there any other reliable way of formatting the text so that I can change the font size without clobbering the other formatting. (Manipulating the RTF directly is OK, I'm not absolutely set on using WinForms to achieve this).
I've given up on trying to go through Winforms to fix this. As I'm applying the change to a whole document (rather than just one portion), it turns out that it's not too hard to modify the RTF directly.
In this case I'm interested in the font size, which is represented by the \fs command. So to replace all the 8.5pt text with 10pt text, you can replace \fs17 with \fs20. (Yes, RTF font sizes come in units of half a point, apparently).
This seems to work well enough, although it does feel like one of those "let's mangle our HTML using regular expressions" type solutions, so I'm not convinced that it's very robust.
Take a look at this:
Changing font for richtextbox without losing formatting
I think it's the same issue. LarsTech's solution is working perfectly for me.

Fastest way to convert RTF to FlowDocument

What is the fastest way to convert a RTF to FlowDocument? I store RTF as plain string and then reload it back, I am using following method,
FlowDocument document = new FlowDocument();
document.SetValue(FlowDocument.TextAlignmentProperty, TextAlignment.Left);
TextRange content = new TextRange(document.ContentStart, document.ContentEnd);
if (content.CanLoad(DataFormats.Rtf) && string.IsNullOrEmpty(rtf) == false)
{
// If so then load it with RTF
byte[] valueArray = Encoding.ASCII.GetBytes(rtf);
using (MemoryStream stream = new MemoryStream(valueArray))
{
content.Load(stream, DataFormats.Rtf);
}
}
But this method is very slow. I need to load many RTFs (around 1000). What can be the trick to make the process fast? Is there any other way around to load a Flowdocument?
You really need to define what you actually need. TextBlock is not weak at all.
It has things to offer ;).
Colours(Background/Foreground + you can color specific part of TextBlock even)
Alignments(you can align TextBlocks as you want, and perhaps even part of them?! Not sure about the last one.
It has TextDecorations, which means it supports bold/italic/underline/strikethrough etc.
Fonts(yeah it supports custom fonts and whatever font you want)
But fair enough. I think you should store FlowDocument XAML instead of actual RTF. This way there will be no conversion and it should be multiple times faster. (See DataFormats.xaml)
Hello Vibhore the TextBlock element should be used when limited text support is required, Label can be used when minimal text support is required.
The FlowDocument element is a container for re-flowable documents that support rich presentation of content, and therefore, has a greater performance impact than using the TextBlock or Label controls.

WPF RichTextBox Control, How To Find All Italicized Words

How can you loop through all the "words" (spaces deliminate words) in an RTB (WPF Control) to see which ones are italicized?
thanks
Well, your task seems to be a quite complicated one.
The contents of a RichTextBox is a FlowDocument which can be found at the property Document. The FlowDocument, in turn, consists of several Blocks.
Each of the Blocks can be a Paragraph, a Section, a Table etc. You'll need to analyze each of them separately.
For the Paragraph, it consists of several Inlines, each of them can be a Span, which in turn may be an Italic. The Italic represents italicized text. The Italic can, in turn, have other inlines, containing other Spans (for example, Hyperlinks, which you may or may not want to include into your result).
You you basically need to traverse all the structure recursively and peek the text from your Italics. A special case may be the words where only a part is italicized, you'll need to have a strategy for them.
I am unaware of any easier methods to achieve what you want. HTH.
Edit:
Perhaps an easier alternate solution would be to traverse all the text using TextPointer from the beginning (richTextBox.Document.ContentStart), switching to the next position with position.GetNextContextPosition(LogicalDirection.Forward), and testing if your current position is inside an Italic using position.Parent. You should however care that Italic can be a non-immediate parent, so you'll perhaps need to traverse several parents upwards. Disclaimer: I did never try this idea in my code.
TextPointer tp = RTB.Document.ContentStart;
TextRange word = WordBreaker.GetWordRange(tp);
while (word.End.GetNextInsertionPosition(LogicalDirection.Forward) != null)
{
if (word.GetPropertyValue(TextElement.FontStyleProperty).ToString() == "Italic")
{
}
word = WordBreaker.GetWordRange(word.End.GetNextInsertionPosition(LogicalDirection.Forward));
}
}
with WordBreaker class from
Link

Paragraph formatting in a WPF RichTextBox?

I need to apply paragraph formatting to a selection in a rich text box. My RTB will behave the same way as the rich text boxes on StackOverflow--the user can type text into the RTB, but they can also enter code blocks. The RTB will apply very simple formatting to the code block--it will change the font and apply a background color to the entire block, similar to what you see in the code block below.
Changing the font is pretty straightforward:
var textRange = new TextRange(rtb.Selection.Start, rtb.Selection.End);
textRange.ApplyPropertyValue(TextElement.FontFamilyProperty, "Consolas");
textRange.ApplyPropertyValue(TextElement.FontSizeProperty, 10D );
Now I need to apply some paragraph-level formatting. I need to set the paragraph margin to 0, so I don't get a blank line between code lines, and I need to set the paragraph background color. Here's my problem: I can't figure out how to get the paragraph elements from the selection, so that I can apply formatting.
Any suggestions? An example of how to apply the Margin and Background properties would be incredibly helpful. Thanks!
Oh, that was easy.. Came across the answer with a little more research:
var textRange = new TextRange(TextBox.Selection.Start, TextBox.Selection.End);
textRange.ApplyPropertyValue(TextElement.FontFamilyProperty, "Consolas");
textRange.ApplyPropertyValue(TextElement.FontSizeProperty, 10D );
textRange.ApplyPropertyValue(Paragraph.MarginProperty, new Thickness(0));
textRange.ApplyPropertyValue(Paragraph.BackgroundProperty, "LightSteelBlue");
The only limitation is that the highlighting still extends only as far as the text, rather than to the right side of the control. I'll leave this question open for a couple of days; if someone can tell me how to extend the background to the right edge of the control, I'll accept your answer to this question.

Resources