WPF ListBox 使用 DataTemplate 显示对象 属性

WPF ListBox showing object property using DataTemplate

我有一个接口的两个实现,包装在另一个 class 中。它看起来像这样:

public interface IMyInterface{
    string someProperty
}

public class MyClass1 : IMyInterface{
    string someProperty
}
public class MyClass2 : IMyInterface{
     string someProperty
}

   public class Wrapper{
       public IMyInterface MyObject {get;}

       public Wrapper(IMyInterface imi){
           MyObject = imi;
       }

       public bool SomeOtherProperty {get; }
   }

现在我有一个 ObservableCollection<Wrapper> Wrappers,我将在 ListBox 中用作 ItemSource。但是我想根据Wrapper.MyObject的类型创建DataTemplate。有什么办法可以实现吗?

您可以(在 ItemsControl 资源中)为每种类型定义一个 DataTemplate。 ItemTemplate 中的 ContentControl 应该选择正确的模板。

<ItemsControl ItemsSource="{Binding Wrappers}">
    <ItemsControl.Resources>
        <DataTemplate DataType="{x:Type vm:MyClass1}">

        </DataTemplate>

        <DataTemplate DataType="{x:Type vm:MyClass2}">

        </DataTemplate>                    
    </ItemsControl.Resources>

    <ItemsControl.ItemTemplate>
        <DataTemplate>
             <ContentControl Content="{Binding MyObject}"/>
        </DataTemplate> 
    </ItemsControl.ItemTemplate>
</ItemsControl>