在PropertyChangedCallback期间更新绑定属性的值
本文关键字:属性 绑定 更新 PropertyChangedCallback | 更新日期: 2023-09-27 18:24:41
我遇到一种情况,需要拦截WPF设置绑定到文本框的属性值的尝试,并更改实际存储的值。基本上,我允许用户在TextBox中输入一个复杂的值,但会自动将其解析为组件。
一切正常,只是我无法让UI刷新并向用户显示新计算的值。
查看模型
public class MainViewModel : INotifyPropertyChanged
{
private string serverName = string.Empty;
public event PropertyChangedEventHandler PropertyChanged;
public string ServerName
{
get
{
return this.serverName;
}
set
{
this.serverNameChanged(value);
}
}
private void NotifyPropertyChanged(String propertyName)
{
if (this.PropertyChanged != null)
{
this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private void serverNameChanged(string value)
{
if (Uri.IsWellFormedUriString(value, UriKind.Absolute))
{
var uri = new Uri(value);
this.serverName = uri.Host;
this.NotifyPropertyChanged("ServerName");
// Set other fields and notify of property changes here...
}
}
}
查看
<TextBox Text="{Binding ServerName}" />
当用户按键/粘贴等时。在"服务器名称"文本框中输入一个完整的URL并制表,视图模型代码就会运行,并且视图模型中的所有字段都设置正确。绑定到UI刷新和显示的所有其他字段。但是,即使ServerName
属性返回正确的值,屏幕上显示的Text
也是旧值。
有没有一种方法可以强制WPF在"源属性更改"过程中获取我的新属性值并刷新显示?
注意:
我也尝试过将ServerName
制作成DependencyProperty
,并在实际的PropertyChangedCallback
中进行工作,但结果是相同的。
正如Bill Zhang所指出的,实现这一点的方法是即使通过调度器也要运行NotifyPropertyChanged
;这将导致事件在当前事件结束后运行,并正确更新显示。
Dispatcher.CurrentDispatcher.BeginInvoke(new Action(() =>
this.NotifyPropertyChanged("ServerName")))