从WPF ListBox中的单个列表中显示多个类型?

问题描述 投票:10回答:2

我有一个包含两种不同类型的ObservableCollection<Object>

我想将此列表绑定到ListBox并为遇到的每种类型显示不同的DataTemplate。我无法弄清楚如何根据类型自动切换数据模板。

我试图使用DataTemplate的DataType属性并尝试使用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));
    }
}
c# wpf data-binding itemtemplate
2个回答
6
投票

你说“它声称它找不到我的类型。”这是你应该解决的问题。

最有可能的问题是,您没有在XAML中创建引用CLR命名空间和程序集的命名空间声明。你需要在XAML的顶级元素中加入这样的东西:

xmlns:foo="clr-namespace:MyNamespaceName;assembly=MyAssemblyName"

一旦你这样做,XAML将知道任何带有XML名称空间前缀foo的东西实际上是MyAssemblyName命名空间中MyNamespaceName中的一个类。

然后,您可以在创建DataTemplate的标记中引用该XML命名空间:

<DataTemplate DataType="{foo:Person}">

你当然可以构建一个模板选择器,但这会为你的软件添加一些不需要的东西。在WPF应用程序中有一个模板选择器的位置,但这不是它。


6
投票

你必须使用DataTemplateSelector。有关示例,请参阅here

有关MSDN的其他信息

© www.soinside.com 2019 - 2024. All rights reserved.