2

I have a class named Data with some public members: Name, Age, Address.

I have also window with text boxes Name, Age, Address.

The Data object can change any time.

How can I bind the Data object to the text boxes and follow after object changes?

I know there is INotifyPropertyChanged and "dependency-properties" but I do not know how to use them.

Edit

public class MyData : INotifyPropertyChanged
{
  private string _name;

  public string Name
  {
    get
    {
      return _name;
    }
    set
    {
      if (_name != value)
      {
        _name = value;
        OnPropertyChnged("Name");
      }
    }
   }
   public event PropertyChangedEventHandler PropertyChanged;

   protected void OnPropertyChanged(string name)
   {
     ProppertyChangedEventHandler handler = PropertyChanged;
     if (handler != null) handler(this, new PropertyChangedEventArgs(name));
   }
}

XAML code:

xmlns:myApp="clr-namespace:MyApp"
<Window.Resources><myApp:MyData x:key = data/></WindowResources>
<TextBox><TextBox.Text><Binding Source="{StaticResource data}" Path="Name" UpdateSourceTrigger="PropertyChanged"/></TextBox.Text></TextBox>

class OtherClass
{
  private MyData data;
  //the window that have the binding textbox
  private MyWindow window;
  public OtherClass()
  {
    data = new MyData();
    data.Name = "new name"
    window = new MyWindow();
    window.show();
  }
}
10
  • Implementing INotifyPropertyChanged should take you 5 minutes: 2 minutes google-ing & 3 minutes copy/pasting it in your code... Learning the syntax to bind your TextBox to an object should take even less time :) Commented Jun 22, 2011 at 12:55
  • Actually I have wpf book and I spend more than 5 min in google and I still dont get it... This is my first time with wpf and all new for me Commented Jun 22, 2011 at 12:58
  • Can you add your code for defining the StaticResource data? Commented Jun 22, 2011 at 14:05
  • Does this build, because you seem to have a couple of typo's, the a is missing in the OnPropertyChanged("Name") and there is an extra p in PropertyChangedEventHandler? Commented Jun 22, 2011 at 14:17
  • 1
    That's a different instance of the class, the view's static resource is constructing it's own instance of the class so the one you create in OtherClass does not get used. You could get rid of the StaticResource and then set the use DataContext of the window to that instance of the class, then change your binding to <TextBox Text="{Binding Name}"/> Commented Jun 22, 2011 at 14:39

2 Answers 2

4

This link from MSDN explains it well.

MSDN link is dead, adding link to a similar article.

When your class property is changed, your property should raise a OnPropertyChanged event with the name of the property so that the View knows to refresh it's binding.

    public String Name
    {
        get { return _name; }
        set 
        {
            if (_name != value)
            {
                _name = value;
                this.OnPropertyChanged("Name");
            }
        }
    }

And your textbox should have a binding such as:

<TextBox Text="{Binding Name}"/>

I have a ViewModelBase class which is where I have implemented my OnPropertyChandedEvent for all derived models to call:

    /// <summary>
    /// An event for when a property has changed.
    /// </summary>
    public event PropertyChangedEventHandler PropertyChanged;

    /// <summary>
    /// Virtual method to call the Property Changed method
    /// </summary>
    /// <param name="propertyName">The name of the property which has changed.</param>
    protected virtual void OnPropertyChanged(String propertyName)
    {
        if (this.PropertyChanged != null)
            this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
    }
Sign up to request clarification or add additional context in comments.

9 Comments

Don't forget that the object holding the Data (ViewModel) must be set as the DataContext of the XAML (View).
True, I had assumed that the poster had figured that out already but I should have stated explicitly.
@Paulie Waulie I probably missing somethig. I did what you wrote and before I create and open the window I put some value in the Data.Name property and nothing show in the relevnt textbox... any idea?
It sounds like the binding is not correct on the TextBox, you could try downloading this tool : wpftutorial.net/Inspector.html, attach to your app and then press control and hover over the TextBox, this will give you a plethora of details about the control. One tab will be DataContext, if that is null then you have not set the data context for the view, otherwise check to see the value of your property in that tab. How are you setting the DataContext for the view?
@Maya Remember to monitor the Output box of Visual Studios for all DataBinding errors, they will appear there.
|
0

Let's the Data class implements INotifyPropertyChanged . Raise the event when someone change the property value on the instances of Data. Then set the proper DataContext to your UI, and bind the single ui element as for example:

<TextBox Text="{Binding Age}"/>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.