数据内容值更改时刷新文本框
本文关键字:刷新 文本 数据 | 更新日期: 2023-09-27 18:26:33
我有几个指南针属性,每侧一个,还有一个方向属性。我将方向绑定到一个组合框,并且在设置指南针点的方向设置器中有一个case语句。
我遇到的问题是UI没有刷新。如果我关闭表单并重新打开它,则数据已更改为正确的值,但UI不会动态更改。
我需要做什么?
对于使用WPF的案例,您正在寻找INotifyPropertyChanged
接口,该接口允许您向UI"发送"带有属性的消息。
主要是在一个名为ViewModelBase:的库中
public class ViewModelBase : INotifyPropertyChanged
{
/// <summary>
/// Raised when a property on this object has a new value
/// </summary>
public event PropertyChangedEventHandler PropertyChanged;
/// <summary>
/// Raises this ViewModels PropertyChanged event
/// </summary>
/// <param name="propertyName">Name of the property that has a new value</param>
protected void SendPropertyChanged(string propertyName)
{
SendPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
/// <summary>
/// Raises this ViewModels PropertyChanged event
/// </summary>
/// <param name="e">Arguments detailing the change</param>
protected virtual void SendPropertyChanged(PropertyChangedEventArgs e)
{
var handler = this.PropertyChanged;
if (handler != null)
{
handler(this, e);
}
}
public void SendPropertyChanged<TProperty>(Expression<Func<TProperty>> property)
{
var lambda = (LambdaExpression)property;
MemberExpression memberExpression;
if (lambda.Body is UnaryExpression)
{
var unaryExpression = (UnaryExpression)lambda.Body;
memberExpression = (MemberExpression)unaryExpression.Operand;
}
else
{
memberExpression = (MemberExpression)lambda.Body;
}
SendPropertyChanged(memberExpression.Member.Name);
}
//.Net 4.5? or 4 and BCL included?
/// <summary>
/// Raises this ViewModels PropertyChanged event
/// </summary>
/// <param name="propertyName">Name of the property that has a new value</param>
protected void SendPropertyChanged([CallerMemberName]string propertyName = "")
{
SendPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
}
在Setter中写入SendPropertyChanged(() => Property)
或SendPropertyChanged("Property")
,UI将更新