简体   繁体   中英

My Dependency Property is only binding one way

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.

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}" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM