【问题标题】:How to force calling the coerceValue of a bindable property when another bindable property change?当另一个可绑定属性更改时,如何强制调用可绑定属性的 coerceValue?
【发布时间】:2019-09-23 10:16:16
【问题描述】:

我有一个这样的自定义控件:

<controls:CustomControl Value=".8" MaxValue=".7"/>

这是Value 可绑定属性:

public static readonly BindableProperty ValueProperty =
            BindableProperty.Create(nameof(Value), typeof(double), typeof(CustomControl), 2d,
                coerceValue: (bindable, value) =>
                 ((double)value).Clamp(0.05d, ((CustomControl)bindable).MaxValue));

问题是它只有在 Value 更改时才会被评估,这不起作用:

<controls:CustomControl Value=".8" MaxValue=".7"/>

但这会:

<controls:CustomControl MaxValue=".7" Value=".8"/>

当另一个属性更改时(即在其propertyChanged 中),是否有办法执行coerceValue

【问题讨论】:

标签: xamarin xamarin.forms bindableproperty


【解决方案1】:

问题是它只有在值改变时才会被评估,这不起作用:

这是一个预期的结果。方法Clamp 将返回限制在最小值和最大值范围内的值。

template<class T>
T Clamp(T x, T min, T max)
{
    if (x > max)
        return max;
    if (x < min)
        return min;
    return x;
}

当你将Value设置为0.7,MaxValue设置为0.8时,因为0.7大于0.05小于0.8,所以它会返回自己(0.7)。并且永远不会调用 propertyChanged 方法。

当您将Value 设置为0.8,MaxValue 设置为0.7 时,它将返回0.8。并且会调用propertyChanged方法。

【讨论】:

  • 抱歉,您有什么解决问题的建议?我只需要MyBindableProperty.CoerceValue
  • 可以在定义可绑定属性时设置默认值(如0)。并处理PropertyChanged中的逻辑。
猜你喜欢
  • 2021-08-22
  • 2012-05-15
  • 1970-01-01
  • 2014-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-14
  • 2018-08-27
相关资源
最近更新 更多