Highlight Text in WPF TextBlock - c#

I am attempting to highlight or set the background of some selected text in a WPF TextBlock.
Say I have 2 text files that I load into memory, complete a diff, and then want to diplay in a WPF App. Imagine looping through each line and then appending text to the textblock and changing color based on Deleted, inserted, or equal text.
for (int i = 0; i < theDiffs.Count; i++)
{
switch (theDiffs[i].operation)
{
case Operation.DELETE:
// set color to red on Source control version TextBlock
break;
case Operation.INSERT:
WorkspaceVersion.AppendText(theDiffs[i].text);
// set the background color (or highlight) of appended text to green
break;
case Operation.EQUAL:
WorkspaceVersion.AppendText(theDiffs[i].text);
// Set the background color (highlight) of appended text to yellow
break;
default:
throw new ArgumentOutOfRangeException();
}
}

You'll want to append Run inline elements to the TextBlock Inlines. Eg (assuming "WorkspaceVersion" is a TextBlock):
case Operation.INSERT:
// set the background color (or highlight) of appended text to green
string text = theDiffs[i].text;
Brush background = Brushes.Green;
var run = new Run { Text = text, Background = background };
WorkspaceVersion.Inlines.Add(run);
break;

Related

UWP/C# How to scroll text from a TextBox to selected text?

I have a UWP Desktop application with Text to Speech capabilities. In it, I have a TextBox to contain the text that will be executed by the Speech Synthesizer. During execution, the application selects the currently executed phrase. However, since the text is larger than the TextBox, I need to scroll the text so that the executed and selected phrase is visible to the user. How to do this? Any help is most welcome.
UWP/C# How to scroll text from a TextBox to selected text?
I'm afraid you can't scroll to specific position wihtin UWP TextBox. It looks does not contains ScrollTo method. However, you could get TextBox's internal ScrollViewer then call ChangeView method to scroll to your wanted position.
For example.
public void ScrollToSp(TextBox control, string text)
{
var grid = (Grid)VisualTreeHelper.GetChild(control, 0);
var position = control.Text.Contains(text);
if (control.Text.Contains(text))
{
var index = control.Text.IndexOf(text);
var rect = control.GetRectFromCharacterIndex(index, true);
for (var i = 0; i <= VisualTreeHelper.GetChildrenCount(grid) - 1; i++)
{
object obj = VisualTreeHelper.GetChild(grid, i);
if (!(obj is ScrollViewer)) continue;
((ScrollViewer)obj).ChangeView(0.0f, rect.Top, 1.0f);
break;
}
}
}

RichText GUI selection color issue when GUI minimized

I have simple Win-form GUI in C# which display the text in red or Green depended upon the value received. The RichText display the text correctly as long as the i do not minimize the GUI. When the GUI is minimized, the text shown in Text window is in black color (only data that was processed when GUI was minimized). when the GUI is maximized the text color for the data shown correctly again.
Please let me know what is wrong here.
Here is my code:
LogMessageWindow.Find(message);
LogMessageWindow.SelectionColor = Color.Red; /// if message&2==0 set color to Red otherwise set color to green
LogMessageWindow.SuspendLayout();
LogMessageWindow.Focus();
LogMessageWindow.AppendText(message + ".\n");
LogMessageWindow.ScrollToCaret();*
In your code you have:
LogMessageWindow.Find(message);
This line is useless: you are Appending a new chunk of Text. Searching for it before appending it won't do much (maybe locate an identical string. Then what?).
LogMessageWindow.SuspendLayout();
SuspendLayout() can be useful if you're adding/appending a large selection of lines of text in batch. When you're finished, you should ResumeLayout(). Doesn't seem to be needed here.
LogMessageWindow.Focus();
Moving the Focus on the RTB control doesn't accomplish anything special. And if the container Form is minimized... Since you're adding text in a procedure, the focus is not needed.
A couple of things you can do.
Using a method, pass a reference to the RichTextBox that is used for this task, the color to use and the text to be appended. Here the new text color is defined as Color? color, so if you pass null, the control ForeColor is used.
RTBAppendWithColor(LogMessageWindow,
((message & 2) == 0) ? Color.Red : Color.Green,
message.ToString() + "\n");
private void RTBAppendWithColor(RichTextBox rtb, Color? color, string AppendedText)
{
int sLenght = AppendedText.Length;
rtb.AppendText(AppendedText);
rtb.Select(rtb.Text.Length - sLenght, sLenght);
if (color != null)
rtb.SelectionColor = (Color)color;
rtb.ScrollToCaret();
}
Using an Extension.
Create a static Class with a static Method that references a RichTextBox object. This method will be a new method of any RichTextBox you create.
LogMessageWindow.AppendWithColor(((message & 2) == 0) ? Color.Red : Color.Green,
message.ToString() + "\n");
public static class RTBExtensions
{
public static void AppendWithColor(this RichTextBox rtb, Color? color, string AppendedText)
{
int sLenght = AppendedText.Length;
rtb.AppendText(AppendedText);
rtb.Select(rtb.Text.Length - sLenght, sLenght);
if (color != null)
rtb.SelectionColor = (Color)color;
rtb.ScrollToCaret();
}
}
If you using FrameWork 3.5, the selection text will probably remain selected even after ScrollToCaret() is called. If it looks ugly, add:
rtb.SelectionStart = rtb.Text.Length;
before rtb.ScrollToCaret().
Thanks al for yur valuable feedback. i was able to get this done by suing this code.
LogMessageWindow.SelectionStart = LogMessageWindow.TextLength; LogMessageWindow.SelectionLength = 0; LogMessageWindow.SelectionColor = Color.Red; LogMessageWindow.SuspendLayout();LogMessageWindow.AppendText(message + ".\n"); LogMessageWindow.ScrollToCaret(); ` LogMessageWindow.ResumeLayout()

How to change font color from C# in WPF

I have created a simple Calendar application and I would like to change the color of names of the days that are displayed. I created a simple condition:
if (nameDay.Text.Equals("Sunday"))
{
daytxt.Foreground = Brushes.Red;
}
But in this case the color is changing permanently. When the name of day changes to "Monday" then color of the text is still red but it should be black. How can I fix my issue?
An else condition is missing from your if statement in order to achieve what you need.
You can do it 1 of 2 ways:
if (nameDay.Text.Equals("Sunday"))
{
daytxt.Foreground = Brushes.Red;
}
else
{
daytxt.Foreground = Brushes.Black;
}
Or
daytxt.Foreground = nameDay.Text.Equals("Sunday") ? Brushes.Red : Brushes.Black;

Conflicting label Foregrounds

I've recently started to learn c#, and I started off by making a simple tic-tac-toe game, using labels and forms.
When I click on a label I want it to change background color and Foreground color.
Here is my code;
public void LabelClick(Label lbl, int i)
{
if (strCurrPlayer == strPlayer1)
{
liP1Squares.Add(i);
lbl.BackColor = System.Drawing.Color.Black;
lbl.ForeColor = System.Drawing.Color.White;
lbl.Text = "X";
}
else
{
//Player2
liP2Squares.Add(i);
lbl.BackColor = System.Drawing.Color.White;
lbl.ForeColor = System.Drawing.Color.Black;
lbl.Text = "O";
}
lbl.Enabled = false;
SwapPlayer();
}
However, when it's called, it sets the background color correctly, but the foregorund, i.e. text, changes from the red, (default) to black for player 1 instead of White, and Light Grey for player 2, instead of Black.
I was wondering if there are any fields within Label or Forms that change text color by default when the background color is changed. If not, what else could be making this change?
Any help would be appreciated.
After you set your items on the label, you are disabling it by
lbl.Enabled = false;
This then causes the label to use the disabled-theme from Windows.
In order to change this behavior, you should turn to using events instead of direct methods.
Every label offers a Click-event that you can use to call a method once the label was clicked.
You can then remove the event-handler from Label.Click and you don't need to disable it.
See MSDN to learn about Control.Click-EventHandler
remove lbl.Enabled = false; to see the changes
after you dissable control it will set the label background color to SystemColors.Control and foreground color to SystemColors.GrayText

How do I change the font of only the highlited text?

I'm making a word processor, and want the user to have the ability to bold only the text you select on windows phone with the tap/hold/drag. I know how to detect what text is selected by the user with Filebox.SelectedText (filebox is the name of the textbox), but have no idea where to go from there - how do I take the text that is selected and ONLY make that selected text bolded?
Note: I am using ComponentOne's Rich Textbox control.
You can make use of the RichTextBox.Selection property.
For example:
private void ModifySelectedText()
{
// Determine if text is selected in the control.
if (richTextBox1.SelectionLength > 0)
{
// Set the color of the selected text in the control.
richTextBox1.SelectionColor = Color.Red;
// Set the font of the selected text to bold and underlined.
richTextBox1.SelectionFont = new Font("Arial",10,FontStyle.Bold | FontStyle.Underline);
// Protect the selected text from modification.
richTextBox1.SelectionProtected = true;
}
}

Categories