How to implement custom helper class for Rich text box?
In this article I am going to discuss how to implement a custom helper class for Rich text box in WPF? I hope this will helpful for any custom work requirement. Please check below code for custom implementation.
Add this helper class for custom implementation.
/// <summary> /// Helper class for creating the custom dependency property for richtextbox to allow to bind the string property to richtextbox's document. /// </summary> public class RichTextBoxHelper : DependencyObject { public static readonly DependencyProperty DocumentTextProperty = DependencyProperty.RegisterAttached( "DocumentText", typeof(string), typeof(RichTextBoxHelper), new FrameworkPropertyMetadata { BindsTwoWayByDefault = true, PropertyChangedCallback = (obj, e) => { var richTextBox = (RichTextBox)obj; // Parse the Text to a document var text = GetDocumentText(richTextBox); var doc = new FlowDocument(); var range = new TextRange(doc.ContentStart, doc.ContentEnd); if (text != null) { range.Load(new MemoryStream(Encoding.UTF8.GetBytes(text)), DataFormats.Text); } // Set the document richTextBox.Document = doc; // When the document changes update the source range.Changed += (obj2, e2) => { if (richTextBox.Document == doc) { MemoryStream buffer = new MemoryStream(); range.Save(buffer, DataFormats.Text); SetDocumentText(richTextBox, Encoding.UTF8.GetString(buffer.ToArray())); } }; } }); public static string GetDocumentText(DependencyObject obj) { return (string)obj.GetValue(DocumentTextProperty); } public static void SetDocumentText(DependencyObject obj, string value) { obj.SetValue(DocumentTextProperty, value); } }
0 comments :
Post a Comment