2014-07-21 171 views
0

我需要一些幫助來解決我有一個簡單的XAML綁定問題。WPF綁定屬性到對象列表

我使用2類MVVM模式。卡和董事會。我已經用卡片創建了一個模型。 Card類由兩個屬性組成。

  1. 我的卡的價值。
  2. 我的卡的狀態(下行或上行)。該板包含一張卡片列表。
public class Card 
{ 
    public int Value { get; private set; } 
    public bool Upside { get; set; } 

    public Card(int value) 
    { 
     this.Value = value; 
    } 
} 

class Board 
{ 
    private List<Card> _cardList = new List<Card>(); 
    public List<Card> CardList 
    { 
     get 
     { 
      return _cardList; 
     } 
     set 
     { 
      if (_cardList == value) 
      { 
       return; 
      } 
      _cardList = value; 
      raisePropertyChanged("CardList"); 
     } 
    } 

    public void Initialize() 
    { 
     // Initialization of the card list 
    } 

    public void FlipCard() 
    { 
     // The rules and actions of my game 
    } 
} 

之後,我加入我的銀行卡和主板性能的所有INotifyPropertyChanged東西。我沒有告訴你代碼保持儘可能清晰。

在我ViewModel我只揭露這一點:

public Board GameBoard { get; set; } 

當然,我有很多其他的方法,屬性和命令,但沒有關於卡。我的比賽和我的牌的規則都在我的板級。我的ViewModel只暴露了特定於我的XAML設計的類。

在我的XAML文件中,我有這樣的東西。一張卡片是一個簡單的矩形。我只需要使用正確的轉換器將我的卡片的值與Fill屬性綁定。這個想法是我只暴露我的董事會,所以我需要寫點類似於

Fill="{Binding **GameBoard.CardList[0]** 

我不會在運行時生成矩形。現在我有4張我的船上,然後我寫了4次矩形碼和硬編碼的4個時間由01結尾的名字,02,03,04,我只是告訴你的01位置:

<Window.Resources> 
    <me:CardFillConverter x:Key="CardConverter"/> 
</Window.Resources> 

<Rectangle x:Name="Card01" Fill="{Binding ??? Converter={StaticResource CardConverter}}" ... /> 

是什麼正確的綁定?

+0

@Alex感謝您的更正 –

回答

0

如果你有你的viewmodel卡的列表,那麼可能你必須以某種方式在你的視圖中顯示它們?將它們與索引器一一對應似乎沒有意義。那麼你或許應該使用類似:

<ItemsControl ItemsSource="{Binding CardList}"> 
<ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Rectangle Fill="{Binding, Converter={StaticResource CardConverter}}"/> 
     </DataTemplate> 
</ItemsControl.ItemTemplate> 
</ItemsControl> 
0

在這裏你去

而不是硬編碼的卡,你可以利用ItemsControl,並指定該卡的外觀和行爲數據模板

<ItemsControl ItemsSource="{Binding GameBoard.CardList}"> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Rectangle Fill="{Binding Value,Converter={StaticResource CardConverter}}"/> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 

您也可以選擇應用ItemsPanelTemplate來定義卡片放置佈局

例如

<ItemsControl ItemsSource="{Binding GameBoard.CardList}"> 
    <ItemsControl.ItemsPanel> 
     <ItemsPanelTemplate> 
      <WrapPanel IsItemsHost="True" /> 
     </ItemsPanelTemplate> 
    </ItemsControl.ItemsPanel> 
    <ItemsControl.ItemTemplate> 
     <DataTemplate> 
      <Rectangle Fill="{Binding Value,Converter={StaticResource CardConverter}}" /> 
     </DataTemplate> 
    </ItemsControl.ItemTemplate> 
</ItemsControl> 
+0

想知道這是否適合您? – pushpraj

1

在轉換器中做你的訣竅。

<Rectangle x:Name="Card01" Fill="{Binding GameBoard.CardList Converter={StaticResource CardConverter} ConverterParameter = 0}" ... />