MKII
MKII

Reputation: 911

How to implement two way Data Binding?

I have a class called ProfileViewModel, that consists of simple properties like so:

class SomeViewModel : INotifyPropertyChanged
    {
        private Foo foo;
        public Foo Foo
            {
                get { return foo; } 
            }

        public string Bar
            {
                get { return foo.bar; }
                set
                    {
                        foo.bar = value;
                        NotifyPropertyChanged ("Bar");
                    }
            }

            // More properties like the above

         public event PropertyChangedEventHandler PropertyChanged;
             protected void NotifyPropertyChanged (string Info)
    {
    if (PropertyChanged != null)
      {
         PropertyChanged (this, new PropertyChangedEventArgs (Info));
      }
    }

I removed some bits that are not really important. Now, I am trying to create a two way binding between some textboxes and the properties of the above class, but nothing seems to work. In the XAML I have tried both:

      <TextBox Margin="5, 25, 5, 0" VerticalAlignment="Top" Height="25" Name="BarField"
               Text="{Binding CurrentFoo.Bar}"/>

and

      <TextBox Margin="5, 75, 5, 0" VerticalAlignment="Top" Height="25" Name="BarField" 
               Text="{Binding Bar, ElementName=CurrentFoo}"/>

neither of which currently work (regardless whether I set it to be Two-Way or not), as nothing appears in the textbox, nor does changing the text in the textbox affect the CurrentFoo object. What exactly is it that I am doing wrong? What is missing here? Do I need to do the binding in the code?

Upvotes: 2

Views: 2727

Answers (1)

E-Bat
E-Bat

Reputation: 4892

For your first binding to work your Foo property must be read/write, currently it is readonly.

For the second approach you do not need to set ElementName, just Mode porperty:

 <TextBox Text="{Binding Bar, Mode=TwoWay}"/>

Note: I prefer the first one.

Upvotes: 3

Related Questions