Display multiple types from a single list in a WPF ListBox?

后端 未结 2 1713
粉色の甜心
粉色の甜心 2020-12-16 01:11

I have an ObservableCollection that contains two different types.

I want to bind this list to a ListBox and display different DataTemplate

相关标签:
2条回答
  • 2020-12-16 01:42

    You have to use a DataTemplateSelector. See here for an example.

    Addiontal information on MSDN

    0 讨论(0)
  • 2020-12-16 01:59

    You say that "it claims it can't find my types." That's a problem that you should fix.

    The problem, most likely, is that you're not creating a namespace declaration in the XAML that references your CLR namespace and assembly. You need to put something like this in the XAML's top-level element:

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

    Once you do this, XAML will know that anything with the XML namespace prefix foo is actually a class in MyAssemblyName in the MyNamespaceName namespace.

    Then you can reference that XML namespace in the markup that created the DataTemplate:

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

    You can certainly build a template selector, but that's adding a piece of cruft to your software that doesn't need to be there. There's a place for template selectors in WPF applications, but this isn't it.

    0 讨论(0)
提交回复
热议问题