简体   繁体   中英

RichEditBox two-way binbing does not work [Windows Store App]

I have RichEditBox and class with DependencyPropert:

public class RichTextC : DependencyObject
{
    public static string GetRichText(DependencyObject obj)
    {
        return (string)obj.GetValue(RichTextProperty);
    }

    public static void SetRichText(DependencyObject obj, string value)
    {
        obj.SetValue(RichTextProperty, value);
    }

    public static readonly DependencyProperty RichTextProperty =  DependencyProperty.Register("RichText", typeof(string), typeof(RichTextC), new PropertyMetadata(string.Empty, callback));

    private static void callback(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var reb = (RichEditBox)d;
        reb.Document.SetText(TextSetOptions.FormatRtf, (string)e.NewValue);
    }
 }

And this is my RichEditBox in XAML file:

<RichEditBox local:RichTextC.RichText="{Binding MyRichText, Mode=TwoWay}"/>

Problem is, that View can be notified by the View Model, but when I change text in RichEditBox it not notify View Model. I mean, binding working only in one way, from View Model to View, but from View to View Model does not work.

How can I change it to two-way binding start working?

You'll need to wire up code to set the RichText property when the RichEditBox's Document's Text changes. To do this handle the RichEditBox.TextChanged event to update the RichText property. You'll need to include some code to prevent the RichText property from updating the RichEditBox's Document's text when handling the TextChanged event (or vice versa) to prevent looping.

Because I cannot comment, I have to rewrite my answer! :-(

  1. Create a class and name it RichEditBoxExtended
  2. Replace the class code with the code from WinRt: Binding a RTF String to a RichEditBox (please recopy I changed the visibility of the class)
  3. Go to your XAML and enter: <local:RichTextBoxExtended RtfText="{Binding MyRichText, Mode=TwoWay}"/>

I hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM