我對WPF比較陌生,它看起來像可能有一堆方法來做到這一點,但我不能得到任何我嘗試過的工作。從WPF列表框的單個列表中顯示多種類型?
我有一個ObservableCollection包含兩種不同的類型。
我想將此列表綁定到列表框,併爲遇到的每種類型顯示不同的DataTemplates。我無法弄清楚如何根據類型自動切換數據模板。
我已經嘗試使用DataTemplate中的數據類型屬性和使用CONTROLTEMPLATES和DataTrigger嘗試,但都無濟於事,要麼什麼也不顯示,或者聲稱無法找到我的類型...
示例嘗試如下:
我現在只有一個數據模板連接到ListBox,但即使這樣也行不通。
XAML:
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<DataTemplate x:Key="PersonTemplate">
<TextBlock Text="{Binding Path=Name}"></TextBlock>
</DataTemplate>
<DataTemplate x:Key="QuantityTemplate">
<TextBlock Text="{Binding Path=Amount}"></TextBlock>
</DataTemplate>
</Window.Resources>
<Grid>
<DockPanel>
<ListBox x:Name="MyListBox" Width="250" Height="250"
ItemsSource="{Binding Path=ListToBind}"
ItemTemplate="{StaticResource PersonTemplate}"></ListBox>
</DockPanel>
</Grid>
</Window>
代碼背後:
public class Person
{
public string Name { get; set; }
public Person(string name)
{
Name = name;
}
}
public class Quantity
{
public int Amount { get; set; }
public Quantity(int amount)
{
Amount = amount;
}
}
public partial class Window1 : Window
{
ObservableCollection<object> ListToBind = new ObservableCollection<object>();
public Window1()
{
InitializeComponent();
ListToBind.Add(new Person("Name1"));
ListToBind.Add(new Person("Name2"));
ListToBind.Add(new Quantity(123));
ListToBind.Add(new Person("Name3"));
ListToBind.Add(new Person("Name4"));
ListToBind.Add(new Quantity(456));
ListToBind.Add(new Person("Name5"));
ListToBind.Add(new Quantity(789));
}
}
+1你說得對。我想知道爲什麼我從來沒有見過這個非常酷的選擇。在這裏,MSDN鏈接:http://msdn.microsoft.com/en-us/library/system.windows.datatemplate.datatype.aspx – HCL 2010-08-04 07:10:09
的DataTemplateSelector似乎像一次克魯夫特我把這個感謝您的建議。我覺得必須有一個簡單的方法來解決這個問題,而且你已經提供了它! – davisoa 2010-08-04 14:47:36