Dante
Dante

Reputation: 3316

How Set And Get data using the same Dependency Property?

I am working on a WPF project. And I just created a dependency property. This dependency property is intended to make the RichTextBox.Selection.Text property bindeable.

But what I cannot do is get and set data to RichTextBox.Selection.Text using the same DP.

This is the code that I used if I ONLY want to get data from my RichTextBox.Selection.Text using binding:

public class MyRichTextBox: RichTextBox
{

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

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

    public MyRichTextBox()
    {         
        this.TextChanged += new TextChangedEventHandler(MyRichTextBox_TextChanged);
    }

    void MyRichTextBox_TextChanged(object sender, TextChangedEventArgs e)
    {
        Text = this.Selection.Text;
    }

And it works perfectly, but with this code I cannot send any data from my ViewModel class.

So, if I ONLY want to set data to the RichTextBox.Selection.Text property from my ViewModel I used this code:

public class MyRichTextBox: RichTextBox
{
    public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
        "Text",
        typeof(string),
        typeof(MyRichTextBox),
        new PropertyMetadata(
            TextPropertyCallback));

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

    private static void TextPropertyCallback(DependencyObject controlInstance, DependencyPropertyChangedEventArgs args)
    {
        MyRichTextBox instance = (MyRichTextBox)controlInstance;
        instance.Selection.Text = (String)args.NewValue;
    }

So, What Can I do if I want to be able to get and set data using the same dependency property???

Hope someone can help me, tahnk you in advance

Upvotes: 0

Views: 263

Answers (1)

Danny Varod
Danny Varod

Reputation: 18068

Instead of binding your input control's text to the VM's property, you have binded an attached property to it, and in that attached property's value changed you set the input control's text.

In other words - there is nothing monitoring the changed to the input control's text.

Edit:

You are still doing:

instance.Selection.Text = (String)args.NewValue;

However, there is no notification of change to instance.Selection.Text.

Upvotes: 1

Related Questions