/// <summary> /// Update the view from the view model /// </summary> private void UpdateFromViewModel() { if (DataContext is TextFormatterViewModel) { // Update the View from the ViewModel (ideally we would automatically data-bind to the RichTextBox, // but this does not appear to be supported, so we do it manually here). var textForDisplay = ((TextFormatterViewModel)DataContext).FormattedText; BlockCollection blocks = MainTextBox.Document.Blocks; for (int i = 0; i < blocks.Count && i < textForDisplay.Count; ++i) { if (blocks.ElementAt <Block>(i) is Paragraph) { // Clear all of the inlines from the paragraph and then add them back from textForDisplay Paragraph p = (Paragraph)blocks.ElementAt <Block>(i); p.Inlines.Clear(); foreach (var txtElem in textForDisplay[i]) { p.Inlines.Add(new Run(txtElem.Item1) { Foreground = txtElem.Item2 ? Brushes.Red : Brushes.Black }); } } } } }
/// <summary> /// Removes an item at a specific index for a block collection. /// </summary> public static void RemoveAt(this BlockCollection collection, int index) { if (index == -1 || collection.Count == 0) { return; } collection.Remove(collection.ElementAt(index)); }
/// <summary> /// Adds an item at a specific index for a block collection. /// </summary> public static void AddAt(this BlockCollection collection, int index, Block item) { if (index == -1) { return; } if (collection.Count == 0) { collection.Add(item); return; } index = Math.Min(index, collection.Count - 1); collection.InsertAfter(collection.ElementAt(index), item); }