2

I'm new to WPF, and I'm doing something which I feel is pretty straightforward. I made a UserControl that contains a textbox, and I want to bind the TextBox.Text property to a dependency property of my usercontrol, Value. The textbox correctly displays Value, and if you change the value of Value, the textbox updates accordingly. But, if I change the value in the Textbox, Value does not change to reflect it. Even if I manually set the binding Mode to two-way, it still only binds one way. I made Value a dependency property, so shouldn't that take care of things?

Here's my XAML (I stripped away the other controls for the sake of readability):

<UserControl x:Class="WindowsApp.FormBox" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WindowsApp"> <Grid DataContext="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=local:FormBox}}"> <TextBox x:Name="TextForm" Text="{Binding Path=Value, Mode=TwoWay}" /> </Grid> </UserControl> 

And here's the c#, Visual Studio auto-generated it for me so maybe there's something not right about it

public String Value { get { return (String)GetValue(ValueProperty); } set { SetValue(ValueProperty, value); } } public static readonly DependencyProperty ValueProperty = DependencyProperty.Register("Value", typeof(String), typeof(FormBox)); 

In other parts of the code, I just assign Value in XAML by just doing Value="{Binding Whatever}" Any advice or help would be appreciated. Thank you.

2
  • When you say "if you change the value in the Textbox, Value does not change to reflect it", do you mean you have typed in a new value or typed in and fully committed the value by forcing that textbox to lose focus? Commented Jun 4, 2014 at 0:57
  • Also, are there any errors in the output log? Commented Jun 4, 2014 at 0:58

1 Answer 1

2

You need to set the Text binding's UpdateSourceTrigger to PropertyChanged. The default for TextBox is LostFocus. If this is the only control in a window then there isn't anything else that can receive focus, so a LostFocus event never fires and the binding never updates the source.

<TextBox x:Name="TextForm" Text="{Binding Path=Value, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}" /> 
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, wow, that was fast, thanks so much! It works! I had just assumed propertychanged would default to default, it didn't occur to me that textbox would have changed that.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.