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

2024-01-04

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

我想将此列表绑定到 ListBox 并为遇到的每种类型显示不同的 DataTemplates。我不知道如何根据类型自动切换数据模板。

我尝试使用 DataTemplate 的 DataType 属性,并尝试使用 ControlTemplates 和 DataTrigger,但无济于事,要么什么也没有显示,要么它声称找不到我的类型...

下面的示例尝试:

我现在只有一个数据模板连接到列表框,但即使这样也不起作用。

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));
    }
}

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

问题很可能是您没有在 XAML 中创建引用 CLR 命名空间和程序集的命名空间声明。您需要将类似这样的内容放入 XAML 的顶级元素中:

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

执行此操作后,XAML 将知道任何带有 XML 命名空间前缀的内容foo实际上是一个类MyAssemblyName in the MyNamespaceName命名空间。

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

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

您当然可以构建一个模板选择器,但这会为您的软件添加一些不需要的东西。 WPF 应用程序中有一处可以放置模板选择器的地方,但这里不是。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 WPF ListBox 中显示单个列表中的多种类型? 的相关文章

随机推荐