代码之家  ›  专栏  ›  技术社区  ›  davisoa

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

  •  10
  • davisoa  · 技术社区  · 15 年前

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

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

    我尝试使用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));
        }
    }
    
    2 回复  |  直到 7 年前
        1
  •  6
  •   Robert Rossney    15 年前

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

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

    一旦您这样做了,XAML就会知道任何带有XML名称空间前缀的东西 foo 实际上是一个班级 MyAssemblyName MyNamespaceName 命名空间。

    DataTemplate :

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

        2
  •  6
  •   HCL    15 年前

    你必须使用 DataTemplateSelector . 看到了吗 here

    附加信息 MSDN

    推荐文章