2017-09-28 74 views
0

我有一個自定義頁面和一個自定義控件。在XAML中填充泛型列表

public class TilesPage : ContentPage 
{ 
    public ObservableCollection<Tile> Tiles 
    { 
     get; 
     set; 
    } 
} 

public class Tile : Frame 
{ 
    public static readonly BindableProperty TitleProperty = BindableProperty.Create(nameof(Title), typeof(string), typeof(Tile), null); 

    public Tile() 
    { 
     HasShadow = false; 
    } 

    public string Title 
    { 
     get 
     { 
      return (string)GetValue(TitleProperty); 
     } 
     set 
     { 
      SetValue(TitleProperty, value); 
     } 
    } 
} 

所以我的頁面有一個瓷磚的集合,即框架。 現在我想通過XAML填充集合。

我的XAML語法時纔是這樣的:

<?xml version="1.0" encoding="utf-8" ?> 
<CPages:TilesPage xmlns="http://xamarin.com/schemas/2014/forms" 
      xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
      x:Class="MyNamespace.AboutPage" 
      xmlns:CControls="clr-namespace:MyNamespace;assembly=MyAssembly" 
      xmlns:CPages="clr-namespace:MyNamespace;assembly=MyAssembly" 
      > 
    <CPages:TilesPage.Tiles> 
     <CControls:Tile Title="Test"> 
      <CControls:Tile.Content> 
       <Label>In Tile</Label> 
      </CControls:Tile.Content> 
     </CControls:Tile> 
    </CPages:TilesPage.Tiles> 
</CPages:TilesPage> 

但集合保持爲空。 XAML不會觸及它。

那麼我的語法有什麼問題?

+0

嘗試使用**依賴屬性**。 –

回答

1

有兩個問題我在代碼中看到:

  1. 我們需要調用InitializeComponent()

    public TilesPage() 
    { 
        InitializeComponent(); 
    } 
    
  2. XAML解析器在這一點上需要一個非空集合的默認構造函數 - 所以它可以添加多個元素。否則它會拋出一個解析異常,或者是 類型不匹配或空值。要解決這個問題,我們需要確保有一個默認值可以使用。

    public ObservableCollection<Tile> _tiles = new ObservableCollection<Tile>(); 
    public ObservableCollection<Tile> Tiles { 
        get { return _tiles; } 
        set { _tiles = value; } 
    } 
    

您現在應該可以看到更新的集合:

protected override void OnAppearing() 
{ 
    base.OnAppearing(); 

    Debug.WriteLine(Tiles?.Count); 
    foreach (var tile in Tiles) 
     Debug.WriteLine(tile.Title); 
} 

此外,建議將這個屬性來綁定 - 用XAML框架(非強制)更易於集成。

public static readonly BindableProperty TilesProperty = 
      BindableProperty.Create(nameof(Tiles), typeof(IList<Tile>), typeof(TilesPage), 
      defaultValue: new ObservableCollection<Tile>()); 

public IList<Tile> Tiles 
{ 
    get 
    { 
     return (IList<Tile>)GetValue(TilesProperty); 
    } 
    set 
    { 
     SetValue(TilesProperty, value); 
    } 
} 
+0

是的,我錯過了InitializeComponents。 – Chris