2017-09-01 38 views
0

比方說,我有一個ObservableCollectionFruit我可以爲每種類型的對象指定一個控件嗎?

public ObservableCollection<Fruit> Fruit {get; set;} 

水果綁定到UserControl(即父母Canvas)呼籲FruitContainer。

fruitContainer.ItemsSource = Fruit; 

但是,有Fruit的子類。

public class Apple : Fruit { ... } 
public class Banana : Fruit { ... } 
public class Strawberry : Fruit { ... } 

而且這些都是ObservableCollection的實際內容。他們也有自己的相關UserControlAppleControlBananaControl

我的問題是,我可以建立一個模板(或別的東西)上FruitContainer使得ItemsSource每個對象類型將自動添加它自己UserControl?如自定義ListBox項目,但每個人都有根據其類型自己的項目...

+0

歡迎前來參觀洽談在[WPF聊天室](https://chat.stackoverflow.com/rooms/18165/wpf),如果你希望有人反彈這樣的問題關閉的.. 。 –

回答

5

當然,你可以定義一個DataTemplate每種類型:

<ItemsControl x:Name="fruitContainer"> 
    <ItemsControl.Resources> 
     <DataTemplate DataType="{x:Type local:Banana}"> 
      <local:BananaUserControl /> 
     </DataTemplate> 
     <DataTemplate DataType="{x:Type local:Apple}"> 
      <local:AppleUserControl /> 
     </DataTemplate> 
    </ItemsControl.Resources> 
</ItemsControl> 
+0

向ItemsControl添加ItemsSource =「{Binding Fruit}」 – Lamelas84

+2

OP似乎以編程方式設置ItemsSource屬性。此外,這與問題無關。 – mm8

1

你的意思是數據模板?您可以在數據模板上指定目標類型。

<DataTemplate x:Key="SomeKey" TargetType="{x:Type local:Apple }"> 
       template goes here 
</DataTemplate> 
相關問題