我在论坛上搜索了一个解决方案,但列出的解决方案中没有一个对此有所帮助。我假设我的实现已经关闭,但我不知道是什么,也不知道为什么。
使用Xamarin表单,当对象的数据被更改时,我试图获得一个更新的标签。
有关守则:
public new event PropertyChangedEventHandler PropertyChanged;
protected new virtual void OnPropertyChanged(string propertyName)
{
System.Diagnostics.Debug.WriteLine ("Before");
if (PropertyChanged != null)
{
System.Diagnostics.Debug.WriteLine ("Fired");
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
}
public string String {
set {
if (_data == value)
return;
_data = value;
OnPropertyChanged ( "String" ); }
get { return _data; }
}
public new View Content {
get {
label = new Label { Text = String };
label.SetBinding( Label.TextProperty, new Binding( "String" ) );
return label;}
}基本上,“以前”被打印到控制台,但是“已启动”不会被打印出来。这意味着PropertyChanged为null,因此PropertyChanged不触发。
我遗漏了什么?
发布于 2015-07-06 21:25:53
我不知道这是否影响到它(可能不会),但是我会将您的属性更改方法重写为以下内容。
protected new virtual void OnPropertyChanged(string propertyName)
{
System.Diagnostics.Debug.WriteLine ("Before");
var handler = this.PropertyChanged;
if (handler == null)
{
return;
}
System.Diagnostics.Debug.WriteLine ("Fired");
handler(this,
new PropertyChangedEventArgs(propertyName));
}获取事件的本地引用将在多线程环境中保护您。这是一种最佳实践,即使您不编写多线程代码。这是一种更安全的处理事件的方法。
请参阅关于堆栈溢出的this answer。
分配给局部变量可以确保如果事件在if和实际调用之间未注册,调用列表将不会为null (因为该变量将拥有原始调用列表的副本)。 这在多线程代码中很容易发生,在检查null和触发事件之间,它可能被另一个线程取消注册。
接下来,我将属性从String重命名为其他内容。我相信.NET框架的实现包括BCL类型字符串。您可能会混淆绑定引擎,尽管它应该足够聪明来识别两者之间的区别。
另外,确保Binding成员的方向设置为Two-Way,并将更新更改通知设置为PropertyChanged。这将确保在更改属性值时始终触发OnPropertyChanged方法。
new Binding("String")
{
Mode = BindingMode.TwoWay,
UpdateSourceTrigger = UpdateSourceTrigger.Explicit,
}https://stackoverflow.com/questions/31255646
复制相似问题