• Bindable WPF RichText Editor with XAML/HTML Convertor


    源码下载   文章来源

    Introduction

    This post will give you some tips/tricks of using Rich Textbox in WPF. As we all know, the build-in WPF RichTexbox doesn’t provide some features that we are looking for so if you are in need of using RichTexbox in WPF project, you should know that you will need to roll your own implementation (at least) a bit. In this post, I will brief you how to make WPF RichTextbox bindable, how to display the HTML in WPF, how to create a Rich Textbox Editor with toolbar.

    Contents

    • Bindable RichTextbox
    • RichText Editor
    • HTML to XAML Conversion

    wpf-rich-text-editor

    Bindable Rich Textbox

    A lot of people asked how to bind RichTextbox on the net. Yes. IMO, the Rich Textbox should be bindable but I’m not sure why Document property of RichText is not a dependency property in WPF ( someone can ask me this question?) but people like us who are using MVVM pattern need to have a binding between RichTextbox and the property of ViewModel.  How are we going to make this happen?

    Well,  we probably need to a custom property that can be bindable in that control so the first thing that come into my mind is the attached property. There maybe a lot of definitations for it but the way I understand is that it is a custom property that can be attached to control. For example: AA property to B Control or etc.

    You can take a look at how Sam implemented the binding support for Passwordbox in his post. (Forget about encrypting the password in memory or etc for now. ) We will follow this approach to implement the binding support in RichTextbox as well.

    The first thing that you might notice is that RichTextbox has the Document property. So, you can create an attached property by wrapping RichTextbox.Document property. Please take a look at siz‘s implementation as below (link: ref).

    class RichTextboxAssistant : DependencyObject
    {
    public static readonly DependencyProperty DocumentProperty =
    DependencyProperty.Register("Document",
    typeof(FlowDocument),
    typeof(RichTextboxAssistant),
    new PropertyMetadata(new PropertyChangedCallback(DocumentChanged)));
     
    private static void DocumentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
    Debug.WriteLine("Document has changed");
    }
     
    public FlowDocument Document
    {
    get { return GetValue(DocumentProperty) as FlowDocument; }
    set { SetValue(DocumentProperty, value); }
    }
    }

    But…… OMG! why it’s so hard to use FlowDocument? How come do we need to call Content.Start and End just to get the text? why not having a property called Text which is a string datatype?

    Yes. it’s ture that using FlowDocument is not so simple compared to a string datatype. we also got the same feeling when we were implemneting this feature. what did we do? We decided to change Document property, a FlowDocument type, to “BoundDocument” which is a string datatype. So, the new code will be like that below. As you can see, it’s a bit complicated then before since we are handling all complex things there.

    public static class RichTextboxAssistant
    {
     
    public static readonly DependencyProperty BoundDocument =
    DependencyProperty.RegisterAttached("BoundDocument", typeof(string), typeof(RichTextboxAssistant),
    new FrameworkPropertyMetadata(null,
    FrameworkPropertyMetadataOptions.BindsTwoWayByDefault,
    OnBoundDocumentChanged));
     
    private static void OnBoundDocumentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
     
    RichTextBox box = d as RichTextBox;
     
    if (box == null)
    return;
     
    RemoveEventHandler(box);
     
    string newXAML = GetBoundDocument(d);
     
    box.Document.Blocks.Clear();
     
    if (!string.IsNullOrEmpty(newXAML))
    {
     
    using (MemoryStream xamlMemoryStream = new MemoryStream(Encoding.ASCII.GetBytes(newXAML)))
    {
     
    ParserContext parser = new ParserContext();
    parser.XmlnsDictionary.Add("", "http://schemas.microsoft.com/winfx/2006/xaml/presentation");
    parser.XmlnsDictionary.Add("x", "http://schemas.microsoft.com/winfx/2006/xaml");
    FlowDocument doc = new FlowDocument();
     
    Section section = XamlReader.Load(xamlMemoryStream, parser) as Section;
    box.Document.Blocks.Add(section);
    }
     
    }
     
    AttachEventHandler(box);
     
    }
     
    private static void RemoveEventHandler(RichTextBox box)
    {
     
    Binding binding = BindingOperations.GetBinding(box, BoundDocument);
     
    if (binding != null)
    {
    if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default ||
    binding.UpdateSourceTrigger == UpdateSourceTrigger.LostFocus)
    {
    box.LostFocus -= HandleLostFocus;
    }
    else
    {
    box.TextChanged -= HandleTextChanged;
    }
    }
     
    }
     
    private static void AttachEventHandler(RichTextBox box)
    {
     
    Binding binding = BindingOperations.GetBinding(box, BoundDocument);
    if (binding != null)
    {
    if (binding.UpdateSourceTrigger == UpdateSourceTrigger.Default ||
    binding.UpdateSourceTrigger == UpdateSourceTrigger.LostFocus)
    {
    box.LostFocus += HandleLostFocus;
    }
    else
    {
    box.TextChanged += HandleTextChanged;
    }
    }
     
    }
     
    private static void HandleLostFocus(object sender, RoutedEventArgs e)
    {
     
    RichTextBox box = sender as RichTextBox;
    TextRange tr = new TextRange(box.Document.ContentStart, box.Document.ContentEnd);
    using (MemoryStream ms = new MemoryStream())
    {
    tr.Save(ms, DataFormats.Xaml);
    string xamlText = ASCIIEncoding.Default.GetString(ms.ToArray());
    SetBoundDocument(box, xamlText);
    }
     
    }
     
    private static void HandleTextChanged(object sender, RoutedEventArgs e)
    {
     
    // TODO: TextChanged is currently not working!
    RichTextBox box = sender as RichTextBox;
    TextRange tr = new TextRange(box.Document.ContentStart,
    box.Document.ContentEnd);
     
    using (MemoryStream ms = new MemoryStream())
    {
    tr.Save(ms, DataFormats.Xaml);
    string xamlText = ASCIIEncoding.Default.GetString(ms.ToArray());
    SetBoundDocument(box, xamlText);
    }
     
    }
     
    public static string GetBoundDocument(DependencyObject dp)
    {
    return dp.GetValue(BoundDocument) as string;
    }
     
    public static void SetBoundDocument(DependencyObject dp, string value)
    {
    dp.SetValue(BoundDocument, value);
    }
     
    }

    Yes. That’s it. You can now simply bind this attached property with a string instead of a flow document.

    <RichTextBox  attached:RichTextboxAssistant.BoundDocument="{Binding Text}" Height="92" />

    RichText Editor

    After implementing the binding support for WPF RichTextbox, we got new requirement that we need to develop a RichText Editor (something like TinyMCE) as well. So, we quickly create a new user control called RichTextEditor.xaml and place a RichTextbox with our attached property. After a few minutes, we got a WPF RichText Editor as below. ( As there are a lot of code snippets already in this post, I’m not going to post it here. Please feel free to take a look at RichTextEditor.xaml in sample project. )

    wpf-rich-text-editor1

    HTML to XAML Conversion

    Our manager was quite happy with our quick and cool solution for implementing WPF Rich Textbox so we checked-in the changes that we made to SVN. and then, the continous integration integrated our latest changes into the new build so people from QA can start testing on our new feature.

    After a few hours, we started getting new bugs regarding to our new RichText Editor from QA. Ouch!

    What happened was that there is one ASP.NET website that is using the same service and same table. The ASP.NET team is using TinyMCE, a Javascript WYSIWYG Editor in that website so those HTML tags which are the output of that editor are being saved in database. That’s why our WPF RichText Editor wasn’t able to render those HTML tags. The same way, their TinyMCE was also having problems with our XAML tags.

    wysiwyg-javascript-editor

    So, what should we do? Ha! I can tell that what’s in your mind now. Yes. a converter! What we need here is a converter that can convert HTML to XAML (vise-versa). Luckily, Microsoft provides a set of classes that can do the conversion for you. You can grab a copy of those classes from this link. (Thank you! MS). We embedded those classes in our application and changed our code as below to support the conversion.

    public static string GetBoundDocument(DependencyObject dp)
    {
    var html = dp.GetValue(BoundDocument) as string;
    var xaml = string.Empty;
     
    if (!string.IsNullOrEmpty(html))
    xaml = HtmlToXamlConverter.ConvertHtmlToXaml(html, false);
     
    return xaml;
    }
     
    public static void SetBoundDocument(DependencyObject dp, string value)
    {
    var xaml = value;
    var html = HtmlFromXamlConverter.ConvertXamlToHtml(xaml, false);
    dp.SetValue(BoundDocument, html);
    }

    That’s is. I already attached all sourcecode in the zip file. Please feel free to download it and play as much as you like. But hey! don’t forget to give the feedback if you found something uncool!.

    Here is how my sample looks like. Happy Wpf-ing!!! :)

    wpf-super-cool-rich-text-editor

  • 相关阅读:
    mysql网文收录
    centos7编译安装memcached
    计算机网络网文
    操作系统网文
    redis网文
    【Leetcode】746. Min Cost Climbing Stairs
    【Leetcode】198. House Robber
    【Leetcode】121. Best Time to Buy and Sell Stock
    【Leetcode】1. Two Sum
    函数的参数 2018-3-27
  • 原文地址:https://www.cnblogs.com/gmth/p/3240140.html
Copyright © 2020-2023  润新知