user3013076
user3013076

Reputation: 525

Binding text box with property inside an object doesn't trigger NotifyPropertyChanged

I have a Property Student which has Name and SchoolName. I have bound the Student.Name property to a textbox

<TextBox Text="{Binding Student.Name, UpdateSourceTrigger=PropertyChanged, Mode=TwoWay}"></TextBox>

My datacontext is

    public class MyDataContext : INotifyPropertyChanged
    {
        private Student _student;
        public Student Student
        {
            get { return _student; }
            set
            {
                if (value != null)
                {
                    _student = value;
                    NotifyPropertyChanged("Student");
                }
            }
        }

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

    public class Student
    {
        public string Name { get; set; }
        public string SchoolName { get; set; }
    }

When I change the text in the textbox NotifyPropertyChanged event is not firing. What am I doing wrong here? How can I achieve this?

Upvotes: 0

Views: 117

Answers (2)

Bradley Uffner
Bradley Uffner

Reputation: 16991

The event isn't being raised because changing the textbox is not actually modifying the Student Reference. It is modifying the value of a property within the student. The way this is written it would only fire if the entire Student property were replaced with a new instance.

To get the behavior you want you should make Student implement INotifyPropertyChanged and update the properties within it to raise the event similar to the way you raise the event on the context.

An alternate solution would be to add proxy properties to your datacontext for the Student properties that just forward the calls to the Student instance.

Upvotes: 1

AwkwardCoder
AwkwardCoder

Reputation: 25631

You need to implement INotifyPropertyChanged on the Student class to get this to work.

The XAML binding framework is monitoring the 'Name' property on the Student class not the Student class.

Upvotes: 1

Related Questions