【发布时间】:2013-07-24 18:20:51
【问题描述】:
我有一种情况,我需要拦截 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 的所有 other 字段都会刷新和显示。但是,即使ServerName 属性返回正确的值,屏幕上显示的Text 也是旧值。
有没有办法强制 WPF 在“源属性更改”过程中获取我的新属性值并刷新显示?
注意:
我也尝试过将ServerName 设为DependencyProperty 并在实际的PropertyChangedCallback 中进行工作,但结果是相同的。
【问题讨论】:
-
我无法重现您的问题。如果在 NotifyPropertyChanged("ServerName") 之后注释掉所有代码,它是否有效?通常可以使用 Dispatcher.CurrentDispatcher.BeginInvoke(new Action(()=> this.NotifyPropertyChanged("ServerName"))) 来实现。
-
您在输出窗口中看到任何错误吗?
-
@BillZhang 实际工作(通过调度程序运行通知);你能把它作为一个答案让我接受吗?
标签: c# wpf dependency-properties inotifypropertychanged