1

I've created a custom control that extends the RichTextBox so that I can create a binding for the xaml property. It all works well as long as I just update the property from the viewmodel but when I try to edit in the richtextbox the property is not updated back.

I have the following code in the extended version of the richtextbox.

    public static readonly DependencyProperty TextProperty = DependencyProperty.Register ("Text", typeof(string), typeof(BindableRichTextBox), new PropertyMetadata(OnTextPropertyChanged));

    private static void OnTextPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var rtb = d as BindableRichTextBox;
        if (rtb == null) 
            return;

        string xaml = null;
        if (e.NewValue != null)
        {
            xaml = e.NewValue as string;
            if (xaml == null)
                return;
        }

        rtb.Xaml = xaml ?? string.Empty;
    }

    public string Text
    {
        get { return (string)GetValue(TextProperty); }
        set { SetValue(TextProperty, value); }
    }

In the view I've set the binding like such

<Controls:BindableRichTextBox Text="{Binding XamlText, Mode=TwoWay}"/>

In the viewmodel I've created the XamlText as a normal property with the NotifyPropertyChanged event being called on updates.

I want the bound XamlText to be updated when the user enters texts in the RichTextBox either on lostfocus or directly during edit, it doesn't really matter.

How can I change the code to make this happen?

Jimmy.Bystrom
  • 297
  • 2
  • 4
  • 15

1 Answers1

0

You will need to listen to changes to the Xaml-property of the BindableRichTextBox and set the Text-property accordingly. There is an answer available here describing how that could be achieved. Using the approach described in that would the result in the following code (untested):

public BindableRichTextBox()
{
    this.RegisterForNotification("Xaml", this, (d,e) => ((BindableRichTextBox)d).Text = e.NewValue);
}

public void RegisterForNotification(string propertyName, FrameworkElement element, PropertyChangedCallback callback)
{
    var binding = new Binding(propertyName) { Source = element };
    var property = DependencyProperty.RegisterAttached(
        "ListenAttached" + propertyName,
        typeof(object),
        typeof(UserControl),
        new PropertyMetadata(callback));
    element.SetBinding(property, binding);
}
Community
  • 1
  • 1
Spontifixus
  • 6,570
  • 9
  • 45
  • 63