简体   繁体   English

在对象内绑定具有属性的文本框不会触发NotifyPropertyChanged

[英]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 我已经将Student.Name属性绑定到文本框

<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. 当我更改文本框中的文本时,NotifyPropertyChanged事件未触发。 What am I doing wrong here? 我在这里做错了什么? How can I achieve this? 我该如何实现?

You need to implement INotifyPropertyChanged on the Student class to get this to work. 您需要在Student类上实现INotifyPropertyChanged才能使其正常工作。

The XAML binding framework is monitoring the 'Name' property on the Student class not the Student class. XAML绑定框架正在监视Student类而不是Student类的'Name'属性。

The event isn't being raised because changing the textbox is not actually modifying the Student Reference. 由于更改文本框实际上并未修改Student参考,因此未引发该事件。 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. 编写方式只有在将整个Student属性替换为新实例后才会触发。

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. 要获得所需的行为,您应该使Student实现INotifyPropertyChanged并更新其中的属性以引发事件,类似于在上下文中引发事件的方式。

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. 另一种解决方案是将代理属性添加到您的datacontext中,以将学生属性仅将调用转发到Student实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM