Say I have an interface like this:
public interface ISomeInterface
{
...
}
I also have a couple of classes implementing this interface;
This answer from Microsoft forums by Beatriz Costa - MSFT is worth reading (rather old):
The data binding team discussed adding support for interfaces a while ago but ended up not implementing it because we could not come up with a good design for it. The problem was that interfaces don't have a hierarchy like object types do. Consider the scenario where your data source implements both
IMyInterface1
andIMyInterface2
and you have DataTemplates for both of those interfaces in the resources: which DataTemplate do you think we should pick up?When doing implicit data templating for object types, we first try to find a
DataTemplate
for the exact type, then for its parent, grandparent and so on. There is very well defined order of types for us to apply. When we talked about adding support for interfaces, we considered using reflection to find out all interfaces and adding them to the end of the list of types. The problem we encountered was defining the order of the interfaces when the type implements multiple interfaces.The other thing we had to keep in mind is that reflection is not that cheap, and this would decrease our perf a little for this scenario.
So what's the solution? You can't do this all in XAML, but you can do it easily with a little bit of code. The
ItemTemplateSelector
property ofItemsControl
can be used to pick whichDataTemplate
you want to use for each item. In theSelectTemplate
method for your template selector, you receive as a parameter the item you will template. Here, you can check for what interface it implements and return theDataTemplate
that matches it.