Xamarin Forms XAML - 创建没有 UI 的自定义控件?

Xamarin Forms XAML - create custom control that has no UI?

假设我想在我的 XAML 中定义一些数据,然后我在同一个 XAML 的多个地方使用这些数据,就像这样:

<custom:Definition Identifier="MyTemplate">
   <custom:Data Value="3" />
   <custom:Data Value="6" />
   <custom:Data Value="12" />
</custom:Definition>

<custom:Control Template="MyTemplate" />
<custom:Control Template="MyTemplate" />
<custom:Control Template="MyTemplate" />

所以 "Template" object 根本不会出现在 UI 中,它只是数据。我在想我可以定义一个从 Element 派生的 object,像这样:

[ContentProperty("Content")]
public class Definition : Element
{
    public static readonly BindableProperty ContentProperty = BindableProperty.Create(nameof(Content), typeof(List<object), typeof(Definition), null);
    public List<object> Content { get; set; }
    public string Identifier {get; set; }
}

但是当我这样做时,XAML 抱怨 "No property, bindable property, or event found for 'Content', or mismatching type between value and property"。

无论我在 'Content' 属性 的类型中输入什么,或者我在标签内的 XAML 中输入什么(即使 Definition 标签有没有 children),我总是收到相同的错误消息。

如何将 non-UI 元素添加到 XAML?

您的可绑定 属性 不应设置为如下所示?

[ContentProperty("Content")]
public class Definition : Element
{
    public static readonly BindableProperty ContentProperty = BindableProperty.Create(nameof(Content), typeof(List<object>), typeof(Definition), null);
    public List<object> Content 
    { 
        get { return (List<object>)GetValue(ContentProperty); } 
        set { SetValue(ContentProperty, value); }
    }
    public string Identifier {get; set; }

    public Definition()
    {
        Content = new List<object>();
    }
}

我喜欢你的目的。对于许多应用程序来说,它是非常可重用的。

您的 class 注入会像图像上突出显示的那样: