evizaer
evizaer

Reputation: 1613

Two-way binding in WPF

I cannot get a two-way bind in WPF to work.

I have a string property in my app's main window that is bound to a TextBox (I set the mode to "TwoWay").

The only time that the value of the TextBox will update is when the window initializes.

When I type into the TextBox, the underlying string properties value does not change.

When the string property's value is changed by an external source (an event on Click, for example, that just resets the TextBox's value), the change doesn't propagate up to the TextBox.

What are the steps that I must implement to get two-way binding to work properly in even this almost trivial example?

Upvotes: 31

Views: 62501

Answers (4)

ΩmegaMan
ΩmegaMan

Reputation: 31721

Make sure that the binding specifies two way and when the property has a change, it is immediately transmitted to the holding property.

 <TextBox Text="{Binding TextBuffer, 
                         UpdateSourceTrigger=PropertyChanged, 
                         Mode=TwoWay}"/>

The above assures that the TextBox input control Text property binds to, then sends the changes back to the string property named TextBuffer in an immediate, PropertyChanged, and TwoWay fashion.

Upvotes: 2

flamandier
flamandier

Reputation: 502

I feel the need to add some precision:

"Two ways" data binding is more than "One way" data binding.

"One way" data binding is a binding from a source to a dependency property. The source must implement INotifyPropertyChanged, in order to get change propagation from source to target.

To get the " 2 way" , so to get a propagation from Target to Source, it depends on the binding mode which you set on the Binding . If you don't set any BindingMode for your binding, the default Binding mode will be used, and this default mode is a characteristics for your target Dependency Property.

Example:

A Textbox bound to a string property, called "MyTextProperty". In the code, you bind Textbox.Text DependencyProperty to "MyTextProperty" on object "MyObject"

--> "one way" binding : the setter of "My TextProperty" must raise an event Property Changed,and "MyObject" must implement INotifyPropertyChanged.

--> "2 ways data binding": in addition to what is needed for "One way", bindingMode must be set to "2 ways". In this special case, the Text DependencyProperty for Textbox does have "2 ways" as default mode, so there is nothing else to do !

Upvotes: 5

Gishu
Gishu

Reputation: 136673

Most probably you're trying to bind to a .net CLR property instead of a WPF dependencyProperty (which provides Change Notification in addition to some other things).
For normal CLR property, you'd need to implement INotifyPropertyChanged and force update on the textbox in the event handler for PropertyChanged.

  • So make your object with the property implement this interface, raise the event in the property setter. (So now we have property change notification)
  • Make sure the object is set as the DataContext property of the UI element/control

This threw me off too when I started learning about WPF data binding.

Update: Well OP, it would have been a waste of time if i was barking up the wrong tree.. anyways now since you had to dig a bit.. you'll remember it for a long time. Here's the code snippet to round off this answer. Also found that updating the textbox happens automatically as soon as I tab-out.. You only need to manually subscribe to the event and update the UI if your datacontext object is not the one implementing INotifyPropertyChanged.

MyWindow.xaml

<Window x:Class="DataBinding.MyWindow" ...
    Title="MyWindow" Height="300" Width="300">
    <StackPanel x:Name="TopLevelContainer">
        <TextBox x:Name="txtValue"  Background="AliceBlue" Text="{Binding Path=MyDotNetProperty}" />
        <TextBlock TextWrapping="Wrap">We're twin blue boxes bound to the same property.</TextBlock>
        <TextBox x:Name="txtValue2"  Background="AliceBlue" Text="{Binding Path=MyDotNetProperty}" />
    </StackPanel>
</Window>

MyWindow.xaml.cs

public partial class MyWindow : Window, INotifyPropertyChanged
{
    public MyWindow()
    {
        InitializeComponent();
        this.MyDotNetProperty = "Go ahead. Change my value.";
        TopLevelContainer.DataContext = this;
    }

    private string m_sValue;
    public string MyDotNetProperty
    {
        get { return m_sValue; }
        set
        {
            m_sValue = value;
            if (null != this.PropertyChanged)
            {
                PropertyChanged(this, new PropertyChangedEventArgs("MyDotNetProperty"));
            }
        }
    }

    #region INotifyPropertyChanged Members
    public event PropertyChangedEventHandler PropertyChanged;
    #endregion
}

Upvotes: 61

Matt Hamilton
Matt Hamilton

Reputation: 204259

We might need to see the code. Does your string property raise a PropertyChanged event? Or (even better) is it implemented as a DependencyProperty? If not, the bound TextBox won't know when the value changes.

As for typing into the TextBox and not seeing the property's value change, that may be because your TextBox isn't losing focus. By default, bound TextBoxes don't write their values back to the source property until focus leaves the control. Try tabbing out of it and seeing if the property value changes.

Upvotes: 3

Related Questions