簡體   English   中英

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" />

因此,“模板”對象根本不會顯示在UI中,而只是數據。 我在想可以定義一個從Element派生的對象,如下所示:

[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抱怨“找不到屬性,可綁定屬性或'Content'事件,或者值和屬性之間的類型不匹配”。

不管我為'Content'屬性的類型放置什么,或者我在標記中的XAML中放置什么(即使Definition標記沒有子代),我總是會收到相同的錯誤消息。

如何將非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>();
    }
}

我喜歡你的目的。 它對於許多應用程序都是非常可重用的。

您的課程的注入就像圖像上突出顯示的那樣:

Element的類層次結構上的類注入

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM