【问题标题】:Trigger other Property from binding从绑定中触发其他属性
【发布时间】:2017-06-09 05:08:30
【问题描述】:
我的 Xamarin Forms 应用程序的一个页面中有两个条目。这两个条目的Text 属性与realm 对象绑定。这是一种双向绑定,所以每当我在这些字段中的任何一个中输入值时,我的领域对象都会更新,反之亦然。这工作得很好。
但我的要求是,当用户更改一个条目中的值时,另一个条目中的值也需要重新计算和更新。这就像有两个用于单位转换的条目(例如 mm-inch) - 当您更改 mm 值时,它会更新另一个字段中的英寸值,反之亦然。我怎样才能实现这种行为?
<Label Text="Speed" />
<Entry x:Name="SpeedEntry" Text="{Binding Speed, Mode=TwoWay}" />
<Label Text="Depth" />
<Entry x:Name="DepthEntry" Text="{Binding Depth, Mode=TwoWay}" />
【问题讨论】:
标签:
c#
xamarin
xamarin.forms
【解决方案1】:
听起来你正在遵循 MVVM 模式(如果你不应该这样做,因为你正在做的就是如何以及为什么使用它的一个主要例子)
我建议将计算放在ViewModel 中,因为它增加了代码重用的机会(跨平台和可能跨项目)
一种方法是使用以下代码 sn-p - 还有很多其他方法 - 包括 Fody.PropertyChanged(减少所需的管道代码数量)、Reactive.UI(用于反应式编程 - 也减少了管道)和类似的库。
using System.ComponentModel;
using System.Runtime.CompilerServices;
public class ConversionViewModel : INotifyPropertyChanged
{
private double depth;
private double speed;
public double Speed {
get { return this.speed; }
set {
this.speed = value;
this.OnPropertyChanged();
this.Depth = this.CalculateDepth();
}
}
public double Depth {
get { return this.depth; }
set {
this.depth = value;
this.OnPropertyChanged();
this.Speed = this.CalculateSpeed();
}
}
public event PropertyChangedEventHandler PropertyChanged;
private double CalculateSpeed()
{
// do your calculation
return 0;
}
private double CalculateDepth()
{
// do your calculation
return 0;
}
protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
this.PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
您可以将计算移至属性 getter 以仅在实际需要时执行它。如果这是一个相对 CPU 密集型计算,您可能希望将结果缓存在一个字段中,并在某些属性更改时使其无效。