StringBuilder sb = new StringBuilder();
sb.Append(
string.Format("{0} |{1} ", Name, Value)
);
Display.Text = sb.ToString(); // Display is a WP7 TextBlock control
I want to make "Name" as bold. Is it possible to do that ?
ChrisF offers the RichTextBox as a solution but its less well known that simple font variation is acheivable with the simple TextBlock:-
myTextBlock.Inlines.Add(new Run() { Text = "Hello " });
myTextBlock.Inlines.Add(new Run() { Text = "World", FontWeight= FontWeights.Bold });
A StringBuilder only contains character data, not formatting. You can't, basically. Unless you are actually generating html or rtf etc.
In the same way that notepad.exe doesn't have bold/italics/etc.
I'm not a WP7 expert, but maybe there is a different control you can use here, more aimed at formatted text.
You'll need to put the text into a RichTextBox and have the name as a separate Run in the Paragraph as in this example from the MSDN:
// Create a Run of plain text and some bold text.
Run myRun1 = new Run();
myRun1.Text = "A RichTextBox with ";
Bold myBold = new Bold();
myBold.Inlines.Add("initial content ");
Run myRun2 = new Run();
myRun2.Text = "in it.";
// Create a paragraph and add the Run and Bold to it.
Paragraph myParagraph = new Paragraph();
myParagraph.Inlines.Add(myRun1);
myParagraph.Inlines.Add(myBold);
myParagraph.Inlines.Add(myRun2);
// Add the paragraph to the RichTextBox.
MyRTB.Blocks.Add(myParagraph);
Related
Is it possible to highlight a part of a text without selecting this part of the text preferably with a different color in Textbox or Rich TextBox? In fact, I mean, a part of the text is highlighted by another color differing from the color assigned for text selection. To clarify, I have attached an image showing this behavior. (The image is from a website, not WPF).
The bold and dark green part is a text which is just highlighted, and the gray region is a selected part.
Using the RichTextBox element allows for more styling options which, to my knowledge, aren't available for the regular TextBox element.
Here is an approach that I have created:
// Generate example content
FlowDocument doc = new FlowDocument();
Run runStart = new Run("This is an example of ");
Run runHighlight = new Run("text highlighting in WPF");
Run runEnd = new Run(" using the RichTextBox element.");
// Apply highlight style
runHighlight.FontWeight = FontWeights.Bold;
runHighlight.Background = Brushes.LightGreen;
// Create paragraph
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(runStart);
paragraph.Inlines.Add(runHighlight);
paragraph.Inlines.Add(runEnd);
// Add the paragraph to the FlowDocument
doc.Blocks.Add(paragraph);
// Apply to RichTextBox
YourRichTextBoxHere.Document = doc;
View Screenshot
I found this article to be helpful.
Highlight Searched Text in WPF ListView
While the article is about highlighting searched text in a ListView, I have easily adapted it in my own code to work with pretty much any control.
Starting with the control you pass in, it will recursively look for TextBlocks and will find the text you want, extract it as an inline, and will change it's Background / Foreground properties.
You can easily adapt the code to be a behavior if your want.
Here is an example:
private void HighlightText(object controlToHighlight, string textToHighlight)
{
if (controlToHighlight == null) return;
if (controlToHighlight is TextBlock tb)
{
var regex = new Regex("(" + textToHighlight + ")", RegexOptions.IgnoreCase);
if (textToHighlight.Length == 0)
{
var str = tb.Text;
tb.Inlines.Clear();
tb.Inlines.Add(str);
return;
}
var substrings = regex.Split(tb.Text);
tb.Inlines.Clear();
foreach (var item in substrings)
{
if (regex.Match(item).Success)
{
var run = new Run(item)
{
Background = (SolidColorBrush) new BrushConverter().ConvertFrom("#FFFFF45E")
};
tb.Inlines.Add(run);
}
else
{
tb.Inlines.Add(item);
}
}
}
else
{
if (!(controlToHighlight is DependencyObject dependencyObject)) return;
for (var i = 0; i < VisualTreeHelper.GetChildrenCount(dependencyObject); i++)
{
HighlightText(VisualTreeHelper.GetChild(dependencyObject, i), textToHighlight);
}
}
}
I hope this is helpful!
I have an array of sentences. Every sentence is a new Run object inside Inlines property of richtextbox`s FlowDocument.
Every sentence have a color.
var paragraph = new Paragraph();
foreach (var sentence in Sentences)
{
....
paragraph.Inlines.Add(new Run { Text = sentence, Background = new SolidColorBrush(color) });
}
tbText.Document.Blocks.Add(paragraph);
When I am editing the sentence like this (I changed 'yes' to 'y1111111111111es' )
I expected to get the same Run object with changed text from 'yes' to 'y1111111111111es' but instead I got 3 Run objects with 'y', '1111111111111111111' and 'es'
That`s how I retrieve the textes
foreach (Paragraph paragraph in tbText.Document.Blocks)
{
foreach (Run inline in paragraph.Inlines)
{
editedTextes.Add(inline.Text);
}
}
Is there any way to edit the text inside native Run object without populating new Run objects when I change the text
It seems FlowDocument dynamically adds runs to encourage wrapping by design.
I see from another stackoverflow post, that if you use a TextBlock instead of runs inside of Paragraphs, you can preserve your text and remove the runs and prevent wrapping.
Try this in your second block:
foreach (Paragraph paragraph in tbText.Document.Blocks)
{
var sb = new StringBuilder();
foreach (Run inline in paragraph.Inlines)
{
sb.Append(inline.Text);
}
editedTextes.Add(new TextBlock()
{
Text = sb.ToString(),
TextWrapping = TextWrapping.NoWrap
});
}
Or just add one run after you have built the string if you don't like the TextBlocks:
editedTextes.Add(sb.ToString());
There are many examples of how to format the text in a TextBox via xaml code, but I am trying to figure out how to change the code in my .cs file.
//TextBox tb initialized in .xaml code
tb.Text = "<bold>Bold</bold> and normal and <italic>Italic</italic>";
is along the lines of what I am looking for. Is this possible?
The end result would look like:
Bold and normal and Italic
You can do that for RichTextBox by adding Inlines like this:
Paragraph paragraph = new Paragraph();
paragraph.Inlines.Add(new Bold(new Run("Bold")));
paragraph.Inlines.Add(new Run(" and normal"));
paragraph.Inlines.Add(new Italic(new Run(" and Italic")));
richTextBox.Document = new FlowDocument(paragraph);
If you decide to use TextBlock you can use the following:
this.myTextBlock.Inlines.Add(new Bold(new Run("Bold")));
this.myTextBlock.Inlines.Add(" and normal and ");
this.myTextBlock.Inlines.Add(new Italic(new Run("italic")));
Otherwise, if you have to use TextBox you can only apply style to whole text, for example using myTextBox.FontWeight.
I'm using the richtextbox to show some Html content in windows phone 7.1.
The html source-code is like:
Paragraph1</p>
<img src="http://www.ifanr.com/wp-content/uploads/2011/11/DSC_332401.jpg" alt="" width="600" height="338" /></p>
Paragraph2。</p>
<h3>Title h3</h3>
Paragraph3。
</p>
Then I use the
"string[] sArray = Regex.Split(html, "</p>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);"
to split them into a Array. Finally, I use the code:
foreach (string array in sArray)
{
Paragraph parag = new Paragraph();
Run run = new Run();
Bold bold = new Bold();
if (!Regex.IsMatch(array.ToString(), #"<img\b[^<>]*?\bsrc\s*=\s*[""']?\s*(?<imgUrl>[^\s""'<>]*)[^<>]*?/?\s*>"))
{
//h3
if (array.ToString().Contains("</h3>"))
{
string hString = array.ToString();
hString = Regex.Replace(hString, "<h3>", "");
string[] hArray = Regex.Split(hString, "</h3>", RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace);
bold.Inlines.Add(hArray[0].ToString());
parag.Inlines.Add(bold);
run.Text = hArray[1].ToString();
parag.Inlines.Add(run);
}
else
{
if(array.ToString().Contains("<blockquote>"))
{
run.Text = Regex.Replace(array.ToString(), "<blockquote>", "blockquote:");
run.FontSize = 18;
}
else
run.Text = array.ToString();
parag.Inlines.Add(run);
}
rtb.Blocks.Add(parag);
}
else
{
//insert the image into richtextbox
Regex regImg = new Regex(#"http://[^\[^>]*?(gif|jpg|png|jpeg|bmp|bmp)", RegexOptions.IgnoreCase);
MatchCollection matches = regImg.Matches(array.ToString());
string result = null;
foreach (Match match in matches)
result = match.Value;
Image image = new Image();
image.Stretch = Stretch.Uniform;
image.Source = new BitmapImage(new Uri(result, UriKind.RelativeOrAbsolute));
InlineUIContainer iuc = new InlineUIContainer();
iuc.Child = image;
parag.Inlines.Add(iuc);
rtb.Blocks.Add(parag);
}
to add some Paragraph or images into the richtextbox, everything goes well in the beginning, but when I Scroll down the richtextbox, the rest paragraph disappear. It confused me all day long, as I could't find out what's wrong with the richtextbox.
Is it just a bug in Windows phone? Any thoughts?
ScreenShot1:
ScreenShot2:
p.s:it doesn't matter whether the html source-code contains some non-english characters or not. This happens when the html source-code is in a large amount of words. These two ScreenShots just show the problem.
The phone applies a restriction that any UIElement can't be larger than 2048 pixels in any direction. This is enforced to avoid performance issues relating to memory and having to draw very large objects. This is to protect you from doing something that greatly affects performance but also has some other reasoning behind it. For example, a phone is a poor device for reading large pieces of text. This applies even more so for dense bodies of text. This size restriction therefore forces you to think about how, or if you should, display large pieces of text within your application.
There are some solutions though.
Rather than using a single Paragrpah or TextBlock for a large "unit" of text, you could consider using something like this: http://blogs.msdn.com/b/priozersk/archive/2010/09/08/creating-scrollable-textblock-for-wp7.aspx
I'm using the RichTextBox.AppendText function to add a string to my RichTextBox. I'd like to set this with a particular colour. How can I do this?
Just try this:
TextRange tr = new TextRange(rtb.Document.ContentEnd, rtb.Document.ContentEnd);
tr.Text = "textToColorize";
tr.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
If you want, you can also make it an extension method.
public static void AppendText(this RichTextBox box, string text, string color)
{
BrushConverter bc = new BrushConverter();
TextRange tr = new TextRange(box.Document.ContentEnd, box.Document.ContentEnd);
tr.Text = text;
try
{
tr.ApplyPropertyValue(TextElement.ForegroundProperty,
bc.ConvertFromString(color));
}
catch (FormatException) { }
}
This will make it so you can just do
myRichTextBox.AppendText("My text", "CornflowerBlue");
or in hex such as
myRichTextBox.AppendText("My text", "0xffffff");
If the color string you type is invalid, it simply types it in the default color (black).
Hope this helps!
Be Aware of TextRange's Overhead
I spent a lot of time tearing my hair out, because TextRange wasn't fast enough for my use-case. This method avoids the overhead. I ran some barebones tests, and its faster by a factor of ~10 (but don't take my word for it lol, run your own tests)
Paragraph paragraph = new Paragraph();
Run run = new Run("MyText");
paragraph.Inlines.Add(run);
myRichTextBox.Document.Blocks.Add(paragraph);
Credit
Note: I think most use cases should work fine with TextRange. My use-case involved hundreds of individual appends, and that overhead stacks up.
Just a complete example which mixes original question with previous remark from Tony
var paragraph = new Paragraph();
var run = new Run(message)
{
Foreground = someBrush
};
paragraph.Inlines.Add(run);
myRichTextBox.Document.Blocks.Add(paragraph);
Now, it is fast and coloured :)
Note that (unlike the TextRange solution) this solution also solved me a line break issue occurring at the first line of the RichTextBox.
I ended up synthesising Omni and Kishores' answers and creating an extension method as so:
public static void AppendText(this System.Windows.Controls.RichTextBox box, string text, SolidColorBrush brush)
{
TextRange tr = new TextRange(box.Document.ContentEnd, box.Document.ContentEnd);
tr.Text = text;
tr.ApplyPropertyValue(TextElement.ForegroundProperty, brush);
}
Which can be called as so:
MyTextBox.AppendText("Some Text\n", Brushes.Green);
the above single line answer:-
myRichTextBox.AppendText("items", "CornflowerBlue")
is not working.The correct way it should be writen is (i am using VS 2017) :-
Dim text1 As New TextRange(myRichTextBox.Document.ContentStart, myRichTextBox.Document.ContentEnd)
myRichTextBox.AppendText("items")
text1.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.CornflowerBlue)