【问题标题】:Force BindableProperty propertyChanged to fire even with same value in Xamarin forms强制 BindableProperty propertyChanged 触发即使在 Xamarin 表单中具有相同的值
【发布时间】: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


    【解决方案1】:

    基于为RecalculateWidth() 发布的代码 - 如果ValueMax 的值未更改,则强制属性更改处理将无济于事,除非this.Width(父控件HealthBar)已经改变。

    所以基本上,你想要做的是每次父控件的宽度发生变化时重新计算子控件的宽度。

    最简单的方法是订阅它的更改:

    protected override void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        base.OnPropertyChanged(propertyName);
    
        if (propertyName == nameof(Width))
            this.RecalculateWidth();
    }
    

    【讨论】:

    • 这不起作用,OnPropertyChanged 事件将与属性本身的 propertyChanged 事件处理程序的触发时间完全相同
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 2018-12-26
    • 2015-01-01
    • 2017-12-27
    • 1970-01-01
    • 2014-04-08
    相关资源
    最近更新 更多