使用INotifyPropertyChanged [英] using of INotifyPropertyChanged
问题描述
有人可以解释一下为什么在wpf中使用绑定时为什么需要使用INotifyPropertyChanged的实现吗?我可以在不实现此接口的情况下绑定属性吗?例如我有代码
Can someone explain me why need to use implementation of INotifyPropertyChanged when using binding in wpf? I can bind properties without implementation of this interface? For example i have code
public class StudentData : INotifyPropertyChanged
{
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
void OnPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
string _firstName = null;
public string StudentFirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
OnPropertyChanged("StudentFirstName");
}
}
}
并绑定到.xaml
<TextBox Text="{Binding Path=StudentFirstName, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
Grid.Row="1"
Grid.Column="2"
VerticalAlignment="Center" />
.xaml.cs中的这段代码
this code from .xaml.cs
StudentData _studentData = new StudentData { StudentFirstName = "John", StudentGradePointAverage = 3.5};
public MainWindow()
{
InitializeComponent();
this.DataContext = _studentData;
}
为什么在这种情况下需要使用INotifyPropertyChanged?这不是我的代码.
why we need to use INotifyPropertyChanged in this case? It is not my code.
推荐答案
如果希望通过代码更改属性时自动更新wpf表单,则需要 INotifyPropertyChanged
.例如,有些控制器可能还想知道是否已进行了编辑以启用/禁用保存按钮.您可能还会在不同的视图上显示相同的属性.在这种情况下, INotifyPropertyChanged
可帮助您在编辑属性时立即更新另一个视图.
You need INotifyPropertyChanged
if you want a wpf form to be automatically updated when a property changes through code. Also some controllers might want to know if edits have been made in order to enable/disable a save-button, for instance. You also might be displaying the same property on different views; in this case INotifyPropertyChanged
helps to immediately update the other view when you edit a property.
如果您认为您的表单在没有 INotifyPropertyChanged
的情况下表现良好,则可以将其删除.
If you think that your form behaves well without INotifyPropertyChanged
, then you can drop it.
请注意,即使没有 INotifyPropertyChanged
,绑定也可以工作.请参阅:为什么绑定更新没有实现INotifyPropertyChanged?
Note that binding works even without INotifyPropertyChanged
. See: Why does the binding update without implementing INotifyPropertyChanged?
我将实现这样的属性.在极少数情况下,它可以帮助避免无休止的循环更新.顺便说一句,它更有效.
I would implement the properties like this. In some rare cases it can help to avoid endless circular updates. And it is more efficient by the way.
private string _firstName;
public string StudentFirstName
{
get { return _firstName; }
set
{
if (value != _firstName) {
_firstName = value;
OnPropertyChanged("StudentFirstName");
}
}
}
从C#6.0(VS 2015)开始,您可以像这样实现 OnPropertyChanged
:
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
这篇关于使用INotifyPropertyChanged的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!