Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make dependency property bind two way in custom control

I have custom control with following:

<TextBox Grid.Column="3" Text="{TemplateBinding SampleValue}" />

public static readonly DependencyProperty SampleValueProperty =
            DependencyProperty.RegisterAttached("SampleValue", typeof(string), typeof(IdattFilterBox), new PropertyMetadata(null));

public string SampleValue
        {
            get { return GetValue(SampleValueProperty) as string; }
            set { this.SetValue(SampleValueProperty, value); }
        }

In a UserControl where I declare my custom control I have XAML like this:

<my:SampleBox SampleValue="{Binding SampleValue, Mode=TwoWay}" />

and ViewModel like so:

public string SampleValue
        {
            get
            {
                return this.sampleValue;
            }

            set
            {
                this.sampleValue = value;
            }
        }

I don't care about INotifyPropertyChanged on VM (so don't tell me about it :) ) Right now it's working as far as displaying text in text box just like I set it in VM. But when I modify this text - it doesn't get bubbled up back into VM.

What should I do? I guess I have to write some code inside custom control? Should I deal with TextBox PART and catch LostFocus? Or how does it work with TemplateBinding?

like image 846
katit Avatar asked Nov 04 '11 02:11

katit


1 Answers

TemplateBinding is only OneWay.

If you are using Silverlight 4, you can try this,

{Binding SampleValue, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}
like image 162
Justin XL Avatar answered Nov 15 '22 13:11

Justin XL