views:

436

answers:

1

Do DependencyPropertys default to two way binding? If not how do you specify?

The reason I ask is that I have the following user control which is causing me problems...

<UserControl x:Class="SilverlightApplication.UserControls.FormItem_TextBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
>

<StackPanel Style="{StaticResource FormItem_StackPanelStyle}" >

    <TextBlock x:Name="lbCaption" Style="{StaticResource FormItem_TextBlockStyle}" />
    <TextBox x:Name="tbItem" Style="{StaticResource FormItem_TextBoxStyle}" />

</StackPanel>

The code behind for which is...

public partial class FormItem_TextBox : UserControl
{

 public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(string), typeof(FormItem_TextBox), new PropertyMetadata(string.Empty, ValueChanged));  
 public static readonly DependencyProperty CaptionProperty = DependencyProperty.Register("Caption", typeof(string), typeof(FormItem_TextBox), new PropertyMetadata(string.Empty, CaptionChanged));

 public string Value
 {
  get { return (String)GetValue(ValueProperty); }
  set { SetValue(ValueProperty, value); }
 }

 public string Caption
 {
  get { return (String)GetValue(CaptionProperty); }
  set { SetValue(CaptionProperty, value); }
 }

 private static void ValueChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
 {
  (source as FormItem_TextBox).tbItem.Text = e.NewValue.ToString();
 }

 private static void CaptionChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
 {   
  (source as FormItem_TextBox).lbCaption.Text = e.NewValue.ToString();
 }

 public FormItem_TextBox()
 {
  InitializeComponent();
 }

}

In my page, I use the control like this....

<UC:FormItem_TextBox Caption="First Name: " Value="{Binding Path=FirstName, Mode=TwoWay}" />

But any updates to the textbox aren't being sent to the model.

If I use the standard text box like this....

<TextBlock Text="Firstname:"/>
<TextBox Text="{Binding Path=FirstName, Mode=TwoWay}" />

Then the two way databinding works perfecly. Any ideas what is wrong with my control?

Cheers,

ETFairfax.

+1  A: 

In your user control you have no way of knowing when the value in the textbox was updated. You need to add an event handler for the TextChanged event on the tbItem textbox and then set the value of the Value property with the new value.

Bryant
Thanks for the response Bryant.I thought it was going to be something like that, but thought it a bit weird because, the ValueChanged has (source as FormItem_TextBox).tbItem.Text = e.NewValue.ToString();...which kind of felt like i was going to be looping round and round; Do you se what I mean?Anyway, what you suggested works, so that's all that matters!!! Thanks.
ETFairfax
The ValueChanged is from the VM to the control. The TextChanged handler is for going back the other direction.
Bryant