I was tasked with creating a partially editable RichTextBox . I saw sentences in Xaml adding TextBlock elements for ReadOnly sections, however this one has an undesirable visual effect that doesn't wrap beautifully. (It should appear as a single block of continuous text.)
I processed the prototype of the working file using reverse string formatting in order to restrict / enable editing and associate it with the dynamic creation of the built-in Run elements for displaying goals. Using the dictionary to store the current values ββof editable sections of the text, I update the Run elements accordingly with any trigger of the TextChanged event - with the idea that if the text of the edited section is completely deleted, it will be replaced with its default value.
On the line: "Hello, NAME, welcome to SPORT Camp," only NAME and SPORT are available.
βββββββββ¦βββββββββ βββββββββ¦βββββββββ Default values: β Key β Value β Edited values: β Key β Value β β ββββββββ¬βββββββββ£ β ββββββββ¬βββββββββ£ β NAME β NAME β β NAME β John β β SPORT β SPORT β β SPORT β Tennis β βββββββββ©βββββββββ βββββββββ©βββββββββ "Hi NAME, welcome to SPORT camp." "Hi John, welcome to Tennis camp."
Problem
Removing the entire text value in a specific session removes this run (and the next run) from the RichTextBox Document . Even though I am adding them back, they no longer display correctly on the screen. For example, using the edited line from the above setting:
The user selects the text "John" and clicks Delete , instead of saving an empty value, it should be replaced by the default text "NAME". Inside it happens. The dictionary gets the correct value, the value of Run.Text matters, the Document contains all the correct Run elements. But the screen displays:
- Expected: "Hi NAME, welcome to the tennis camp."
- In fact: "Hello, NAMETennis camp."

Sidenote: This lost-work behavior can also be duplicated on insertion. Highlight SPORT and paste Tennis and Run containing the camp. lost.
Question
How to keep each Run element visible even through destructive actions after replacing them?
Code
I tried breaking the code into a minimal example, so I deleted:
- Every
DependencyProperty and related binding in xaml - Logical recalculation of the carriage position (sorry)
- Implemented a method for expanding the formatting of related strings from the first link to a single method contained within the class. (Note: this method will work for simple sample string formats. My code has been excluded for more reliable formatting. Therefore, please follow the example provided for these testing purposes.)
- Made editable sections clearly visible, regardless of the color scheme.
To verify, drop the class into the resource folder of the WPF project, correct the namespace and add the control to the view.
using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; namespace WPFTest.Resources { public class MyRichTextBox : RichTextBox { public MyRichTextBox() { this.TextChanged += MyRichTextBox_TextChanged; this.Background = Brushes.LightGray; this.Parameters = new Dictionary<string, string>(); this.Parameters.Add("NAME", "NAME"); this.Parameters.Add("SPORT", "SPORT"); this.Format = "Hi {0}, welcome to {1} camp."; this.Text = string.Format(this.Format, this.Parameters.Values.ToArray<string>()); this.Runs = new List<Run>() { new Run() { Background = Brushes.LightGray, Tag = "Hi " }, new Run() { Background = Brushes.Black, Foreground = Brushes.White, Tag = "NAME" }, new Run() { Background = Brushes.LightGray, Tag = ", welcome to " }, new Run() { Background = Brushes.Black, Foreground = Brushes.White, Tag = "SPORT" }, new Run() { Background = Brushes.LightGray, Tag = " camp." }, }; this.UpdateRuns(); } public Dictionary<string, string> Parameters { get; set; } public List<Run> Runs { get; set; } public string Text { get; set; } public string Format { get; set; } private void MyRichTextBox_TextChanged(object sender, TextChangedEventArgs e) { string richText = new TextRange(this.Document.Blocks.FirstBlock.ContentStart, this.Document.Blocks.FirstBlock.ContentEnd).Text; string[] oldValues = this.Parameters.Values.ToArray<string>(); string[] newValues = null; bool extracted = this.TryParseExact(richText, this.Format, out newValues); if (extracted) { var changed = newValues.Select((x, i) => new { NewVal = x, Index = i }).Where(x => x.NewVal != oldValues[x.Index]).FirstOrDefault(); string key = this.Parameters.Keys.ElementAt(changed.Index); this.Parameters[key] = string.IsNullOrWhiteSpace(newValues[changed.Index]) ? key : newValues[changed.Index]; this.Text = richText; } else { e.Handled = true; } this.UpdateRuns(); } private void UpdateRuns() { this.TextChanged -= this.MyRichTextBox_TextChanged; foreach (Run run in this.Runs) { string value = run.Tag.ToString(); if (this.Parameters.ContainsKey(value)) { run.Text = this.Parameters[value]; } else { run.Text = value; } } Paragraph p = this.Document.Blocks.FirstBlock as Paragraph; p.Inlines.Clear(); p.Inlines.AddRange(this.Runs); this.TextChanged += this.MyRichTextBox_TextChanged; } public bool TryParseExact(string data, string format, out string[] values) { int tokenCount = 0; format = Regex.Escape(format).Replace("\\{", "{"); format = string.Format("^{0}$", format); while (true) { string token = string.Format("{{{0}}}", tokenCount); if (!format.Contains(token)) { break; } format = format.Replace(token, string.Format("(?'group{0}'.*)", tokenCount++)); } RegexOptions options = RegexOptions.None; Match match = new Regex(format, options).Match(data); if (tokenCount != (match.Groups.Count - 1)) { values = new string[] { }; return false; } else { values = new string[tokenCount]; for (int index = 0; index < tokenCount; index++) { values[index] = match.Groups[string.Format("group{0}", index)].Value; } return true; } } } }