2016-06-07 90 views
0

我只想創建一個Xamarin.Forms自定義控件。這個自定義控件應該在xaml中獲取一個數組/視圖列表(例如,像Stacklayout)。像Xamarin.Forms像StackLayout自定義控件

我的XAML看起來像這樣:

<controls:MyLayout> 
    <ContentView BackgroundColor="Green"> 
     <Label Text="Test 1" /> 
    </ContentView> 

    <ContentView BackgroundColor="Red"> 
     <Label Text="Test 1" /> 
    </ContentView> 
</controls:MyLayout> 

而且類MyLayout

[ContentProperty("Children")] 
public class MyLayout: ScrollView, IViewContainer<View> 
{ 
    public IList<View> Children { get; set; } 

    // And some more properties and methods ... 
} 

但是,當我編譯這個和我的Android手機上運行它,我得到以下錯誤:

Exception has been thrown by the target of an invocation. ---> Xamarin.Forms.Xaml.XamlParseException: Position 29:8. Cannot assign property "Children": type mismatch between "Xamarin.Forms.ContentView" and "System.Collections.Generic.IList`1[Xamarin.Forms.View]"

我該如何解決這個問題?我錯過了什麼?

+0

無,那不是問題。與'ContentView'我得到了同樣的錯誤:「Xamarin.Forms.ContentView」和「System.Collections.Generic.IList'1 [Xamarin.Forms.ContentView]」之間的類型不匹配「 – Joehl

+2

您可以參考'Xamarin.Forms'源創建你的控件,現在它是開源的。你可以在https://github.com/xamarin/Xamarin.Forms找到代碼 –

回答

-1

你需要把物品放入容器中,如:

<ContentView BackgroundColor="Red"> 
     <Label Text="Test 1" /> 
    </ContentView> 
</x:Array> 

但我認爲它不是一個好方法。您可以創建視圖集合類像下面,並用它在你的代碼,所以你可以看到,如果事情添加到它運行時:

public class ViewCollection : ObservableCollection<View> 
{ 

} 


<controls:MyLayout> 
    <local:ViewCollection Type="{x:Type View}"> 
     <ContentView BackgroundColor="Green"> 
      <Label Text="Test 1" /> 
     </ContentView> 

     <ContentView BackgroundColor="Red"> 
      <Label Text="Test 1" /> 
     </ContentView> 
    </local:ViewCollection> 
</controls:MyLayout> 

您還需要更改Children物業類型ViewCollection