【问题标题】:Why BindingProperty get value only once from changing value of ViewModel on Xamarin.Forms为什么 BindingProperty 只能从 Xamarin.Forms 上更改 ViewModel 的值中获得一次价值
【发布时间】:2016-02-21 06:11:30
【问题描述】:

我创建了具有 BindableProperty 的自定义视图。 我将此 BindableProperty 绑定到 ViewModel 的值。 我还将 Label.Text 绑定到相同的值。 当该值更改时,Label.Text 会正确更改,但 BindableProperty 不会使这些更改。 它得到第一个值,但没有改变值。

BindingProperty 如下所示。它有一些调试代码要检查。“ratio-ing”和“ratio”只出现一次。

#region BarRatio BindableProperty
public static readonly BindableProperty BarRatioProperty =
    BindableProperty.Create<DepthBarView, double>(
        p => p.BarRatio, default(double),

        propertyChanging: (bindable, oldValue, newValue) =>
        {
            Debug.WriteLine("ratio-ing {0}", newValue);
        },
        propertyChanged: (bindable, oldValue, newValue) =>
        {
            try
            {
                Debug.WriteLine("ratio-{0}", newValue);
                var owner = ((DepthBarView)bindable);
                owner.boxView.WidthRequest = owner.Width * newValue;
                owner.BarRatio = newValue;
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.ToString());
            }
        },
        coerceValue: (bindable, newValue) =>
        { return newValue; });

BindablePropery 的用法如下。

<Grid>
  <views:DepthBarView VerticalOptions="Start"
                    Fill="Blue"
                    HeightRequest="5"
                    BarHorizontalOptions="Start"
                    BarRatio="{Binding Value}"></views:DepthBarView>
  <Label Text="{Binding Value}"
       VerticalOptions="Start"></Label>
</Grid>

任何建议都是有帮助的。 完整的复制代码在这里。 test.zip

【问题讨论】:

  • 天哪,那是 Xamarin 代码吗?它非常难以阅读。
  • 你说的是像 xxx: 这样的语法吗?这是正常的 C# 功能。
  • 不,我的意思是BindableProperty,它看起来并不容易。
  • 我不认为与 WPF 相比有很大的不同。 stackoverflow.com/questions/17629945/…

标签: c# xaml xamarin.forms


【解决方案1】:

您需要在每次更新时触发OnPropertyChanged 事件。

查看this 帖子了解如何实现INotifyPropertyChange 接口。

【讨论】:

  • 在我的代码中,NotifyPropertyChanged 的​​工作方式类似于链接帖子的 OnPropertyChanged。
  • 当值改变标签的文本获取值,但我的 BindableProperty 没有。
【解决方案2】:

如果我注释掉“owner.BarRatio = newValue;”这一行,这行得通

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多