2
using System.Collections.Generic;
3
using System.Globalization;
8
using System.Threading.Tasks;
10
using System.Windows.Controls;
11
using System.Windows.Data;
12
using System.Windows.Documents;
13
using System.Windows.Markup;
15
namespace ViewModel.Services
17
public class RichTextBoxHelper : DependencyObject
19
private static HashSet<Thread> _recursionProtection = new HashSet<Thread>();
21
public static string GetDocumentXaml(DependencyObject obj)
23
return (string)obj.GetValue(DocumentXamlProperty);
26
public static void SetDocumentXaml(DependencyObject obj, string value)
28
_recursionProtection.Add(Thread.CurrentThread);
29
obj.SetValue(DocumentXamlProperty, value);
30
_recursionProtection.Remove(Thread.CurrentThread);
33
public static readonly DependencyProperty DocumentXamlProperty = DependencyProperty.RegisterAttached(
36
typeof(RichTextBoxHelper),
37
new FrameworkPropertyMetadata(
39
FrameworkPropertyMetadataOptions.AffectsRender | FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
42
if (_recursionProtection.Contains(Thread.CurrentThread))
45
var richTextBox = (RichTextBox)obj;
47
// Parse the XAML to a document (or use XamlReader.Parse())
51
var stream = new MemoryStream(Encoding.UTF8.GetBytes(GetDocumentXaml(richTextBox)));
52
var doc = (FlowDocument)XamlReader.Load(stream);
55
richTextBox.Document = doc;
59
richTextBox.Document = new FlowDocument();
62
// When the document changes update the source
63
richTextBox.TextChanged += (obj2, e2) =>
65
RichTextBox richTextBox2 = obj2 as RichTextBox;
66
if (richTextBox2 != null)
68
SetDocumentXaml(richTextBox, XamlWriter.Save(richTextBox2.Document));