1

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?

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

5 Comments

This will just show the ToString() of Wrapper. How can I tell WPF to pick the object property inside the Wrapper, I can't use DisplayMemberPath since it's not a simple string value
@SZT, my mistake, I misunderstood your issue. please see the edit. ContentControl in ItemTemplate should in theory pick correct template
@SZT, maybe I wrote smth overcomplicated. If template for MyClass1 and MyClass2 are not using their unique properties, and using only common properties from interface, then you can declare only ItemsControl.ItemTemplate, e.g. like this: <DataTemplate><TextBlock Text="{Binding MyObject.Text}"/></DataTemplate>. I adressed the issue of different templates for different interface implementations mostly
no you are on the right track. I am showing different icons based on the class type. Here's I got another question though, is there a way where I can show the common properties, and then have a DataTemplate just to pick my icon based on the class type?
@SZT, you can make an IValueConverter for icon. Bind MyObject using that converter, and return different icons based on real type (value.GetType())

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.