使用Xamarin C#创建可绑定属性,找不到属性,找到可绑定属性

Sna*_*yes 1 c# xamarin.forms

我创建了一个派生自StackLayout以下的类:

public class MyStackLayout : StackLayout
{
    private readonly BindableProperty TriggerTypeProperty = BindableProperty.Create("TriggerType", typeof(string), typeof(MyStackLayout), defaultValue: "test", propertyChanged: (b, o, n) => OnTriggerTypePropChanged(b, (string)o, (string)n));

    public string TriggerType
    {
      get
      {
        return (string)GetValue(TriggerTypeProperty);
      }
      set
      {
        SetValue(TriggerTypeProperty, value);
      }
    }

    private static void OnTriggerTypePropChanged(BindableObject bindable, string oldvalue, string newvalue)
    {
      var obj = bindable as MyStackLayout;
      if (obj == null)
      {
        return;
      }

      obj.TriggerType = newvalue;
    }
}
Run Code Online (Sandbox Code Playgroud)

在XAML中:

<controls1:MyStackLayout IsVisible="False" TriggerType="{Binding AStringPropertyFromViewModel}">
   ...
</controls1:MyStackLayout>
Run Code Online (Sandbox Code Playgroud)

我收到了错误:

没有找到"TriggerType"的属性,可绑定属性或事件,或者值和属性之间的类型不匹配.

怎么了 ?

如果我在XAML中使用TriggerType="A string"工作正常,如果我使用{Binding ...}将无法正常工作.

小智 7

根据Xamarin文档,以下是如何定义可绑定属性:

public static readonly BindableProperty EventNameProperty =
BindableProperty.Create ("EventName", typeof(string),typeof(EventToCommandBehavior), null);
Run Code Online (Sandbox Code Playgroud)

尝试将可绑定属性从私有更改为公共,以查看它是否解决了您的问题.

文档的链接:https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/bindable-properties