CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Sep 2005
    Location
    Cracow, Poland
    Posts
    345

    Simple databinding scenario

    I`m trying to simulate simple two-way databinding mechanism. I have declared simple class for that purpose:

    Code:
    public class Car : INotifyPropertyChanged
         {        
             string color;
     
             public string Color
             {
                 get { return color; }
                 set
                 {
                     color = value;
                     OnPropertyChanged("Color");
                 }
             }
     
             
             
             public event PropertyChangedEventHandler PropertyChanged;
     
             void OnPropertyChanged(string propertyName)
             {
                 if (PropertyChanged != null)
                 {
                     PropertyChanged(null, new PropertyChangedEventArgs(propertyName));
                 }
             }

    I have also created object of that class in Window1.cs file:


    Code:
    public partial class Window1 : Window
         {
             Car veh = new Car();
     
     
             public Window1()
             {
                 InitializeComponent();
     
                 veh.Color="red";
     
                 this.DataContext = veh;
             }
     ...

    I have binded this object`s color property for a textbox:


    Code:
     <TextBox Canvas.Left="276" Canvas.Top="66" Height="19.277" Width="101">
                 <TextBox.Text>
                     <Binding Path="Color" Mode="TwoWay"></Binding>
                 </TextBox.Text>
             </TextBox>

    Value in this textbox doesn`t refresh however when property of business object changes. What is wrong?
    Last edited by gstercken; April 17th, 2009 at 10:12 AM. Reason: Added code tags

  2. #2
    Join Date
    Sep 2002
    Location
    14° 39'19.65"N / 121° 1'44.34"E
    Posts
    9,815

    Re: Simple databinding scenario

    This happens because in your OnPropertyChanged() implementation, you are passing null as the source object. You should pass a reference to the changed object ('this', in this case) instead:

    Code:
    void OnPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured