Matt
Matt

Reputation: 1422

Binding in my user control isn't working

I have a User control I've created called TextBoxAndMore that contains a textbox (called textBox1) with a "more" button beside it. On this user control, I have a property called Text. I'd like this Text property to mirror the text in the textbox.

I'd like this property to be bindable, so that in my XAML I can bind it to a String property called Description in my ViewModel, like this:

<my:TextBoxAndMore Text="{Binding Path=Description}" />

So I have the following code (generated by the propdb snippet):

    // Using a DependencyProperty as the backing store for Text.  This enables animation, styling, binding, etc...
    public static readonly DependencyProperty TextProperty =
        DependencyProperty.Register("Text", typeof(String), typeof(TextBoxAndMore),
        new UIPropertyMetadata(String.Empty));

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

And, on the text box, I have this code attached to the TextChanged event handler, the idea being that when the user types in the textbox, the Text property of this user control changes with it:

    private void textBox1_TextChanged(object sender, TextChangedEventArgs e)
    {
        Text = textBox1.Text;
    }

However, the end result is that the binding simply doesn't appear to work. There's no errors in the output window, and my Description property in my ViewModel just doesn't get set (it remains null).

I'm sure it's something obvious, but I'm quite new to WPF and would appreciate some guidance.

Upvotes: 2

Views: 364

Answers (1)

Aardvark
Aardvark

Reputation: 8561

I think you need to configure 2-way binding:

<my:TextBoxAndMore Text="{Binding Path=Description Mode=TwoWay}" />

You could also remove the TextChanged event code in the control and also use TwoWay binding to the control's Text property.

Edit:

<-> == two-way binding...

TextBlockInControlsTemplate <-> TextDepPropInControl <-> DescriptionPropInVM

Upvotes: 2

Related Questions