【发布时间】:2018-09-15 11:49:19
【问题描述】:
我在自定义控件 (HealthBar) 中有一个可绑定属性:
public static readonly BindableProperty ValueProperty = BindableProperty.Create(
nameof(Value),
typeof(int),
typeof(HealthBar),
0,
BindingMode.TwoWay,
propertyChanged: ValueChanged);
即使我为属性设置了相同的值,是否可以强制触发 propertychanged(ValueChanged 方法)? ValueChanged 方法正在做一些计算来设置健康栏的宽度。
private static void ValueChanged(BindableObject bindable, object oldValue, object newValue)
{
HealthBar obj = bindable as HealthBar;
if (obj != null)
{
obj.RecalculateWidth();
}
}
我知道这听起来有点疯狂,所以这里有更多细节;我需要强制栏重新计算宽度,因为列表视图中有一些这样的宽度,并且向 ObservableCollection 添加更多会导致宽度混乱。每 2 秒通过 signalR 更新值,因此下次设置 Value 属性时应显示正确的宽度。
为了清楚起见,这里是重新计算宽度的代码:
private void RecalculateWidth()
{
double val = this.Value;
double max = this.Max;
double percent = (val / max) * 100;
double width = (double)this.Width * (double)percent / 100;
this.bar.Layout(new Rectangle(0, 0, width, this.Height));
}
【问题讨论】:
标签: c# xamarin.forms binding