Search code examples
c#wpfdata-bindinglistboxdatatemplate

WPF ListBox showing object property using DataTemplate


I have two implementation of an interface, that is wrapped in another class. It looks like this:

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

Now I have a ObservableCollection<Wrapper> Wrappers, that I'm gonna use as ItemSource in ListBox. But I want to create DataTemplate based on the type of Wrapper.MyObject. Is there any way to achieve that?


Solution

  • you can define (in ItemsControl Resources) a DataTemplate for each type. ContentControl in ItemTemplate should pick correct template.

    <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>