首页 > 解决方案 > bindableProperty 无法获取值?

问题描述

我在自定义视图中创建了一个可绑定属性,但它无法获得价值。

这是代码:

public string BackgroundImage
        {
            get
            {
                var image = (image)GetValue(BackgroundImageProperty);
                return image;
            }
            set => SetValue(BackgroundImageProperty, value);
        }

图像为空。

public static readonly BindableProperty BackgroundImageProperty = BindableProperty.Create(nameof(BackgroundImage), typeof(string), typeof(MyView), null);

xml代码:

<local:MyView BackgroundImage="back.png" />

我确实想提供一个字符串值并将其提供给图像。我在 xaml 中给 BackgroundImage 一个字符串值。

标签: xamarin.forms

解决方案


解决方案1: 可以从事件propertyChanged中获取值

public static readonly BindableProperty TextProperty = BindableProperty.Create(
 nameof(Text),
 typeof(string),
 typeof(MyView),
 null,
 propertyChanged: (bindable, oldValue, newValue) =>
 {
   var value = newValue;
   // do some thing you want .
 }
);

解决方案 2: 您可以 在 CustomView中设置BindingContext 。

public MyView
{
  //...
  BindingContext = this;
  //...
}

推荐阅读