代码之家  ›  专栏  ›  技术社区  ›  Noobie3001

强制BindableProperty属性更改为激发,即使在Xamarin窗体中具有相同的值

  •  0
  • Noobie3001  · 技术社区  · 6 年前

    我在自定义控件(HealthBar)中有一个可绑定属性:

        public static readonly BindableProperty ValueProperty = BindableProperty.Create(
            nameof(Value),
            typeof(int),
            typeof(HealthBar),
            0,
            BindingMode.TwoWay,
            propertyChanged: ValueChanged);
    

        private static void ValueChanged(BindableObject bindable, object oldValue, object newValue)
        {
            HealthBar obj = bindable as HealthBar;
            if (obj != null)
            {
                obj.RecalculateWidth();
            }
        }
    

    我知道这听起来有点疯狂,所以这里有一些更详细的信息;我需要强制条重新计算宽度,因为在listview中有一些这样的内容,并且向ObservableCollection添加更多内容会导致宽度混乱。值每2秒通过信号器更新一次,因此下次设置值属性时应显示正确的宽度。

    以下是为清晰起见重新计算宽度的代码:

        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));
        }
    
    1 回复  |  直到 4 年前
        1
  •  0
  •   Sharada    6 年前

    根据发布的代码 RecalculateWidth() -如果 Value Max this.Width HealthBar

    所以基本上,您要做的是每次父控件的宽度更改时重新计算子控件的宽度。

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

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