使用 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 中绑定
And binding in .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屋!