views:

1299

answers:

5

Hi,

Say I have an interface like this:

public interface ISomeInterface
{
...
}

I also have a couple of classes implementing this interface;

public class SomeClass : ISomeInterface
{
...
}

Now I have a WPF ListBox listing items of ISomeInterface, using a custom DataTemplate.

The databinding engine will apparently not (that I have been able to figure out) allow me to bind to interface properties - it sees that the object is a SomeClass object, and data only shows up if SomeClass should happen to have the bound property available as a non-interface property.

How can I tell the DataTemplate to act as if every object is an ISomeInterface, and not a SomeClass etc.?

Thanks!

+4  A: 

The short answer is DataTemplate's do not support interfaces (think about multiple inheritance, explicit v. implicit, etc). The way we tend to get around this is to have a base class things extend to allow the DataTemplate specialization/generalization. This means a decent, but not necessarily optimal, solution would be:

public abstract class SomeClassBase
{

}

public class SomeClass : SomeClassBase
{

}

<DataTemplate DataType="{x:Type local:SomeClassBase}">
    <!-- ... -->
</DataTemplate>
sixlettervariables
Thanks - I'll accept your answer even though this means I pretty much have to rework quite a bit of stuff to do what I want. Some times life sucks when you're tasked with putting a WPF UI on top of a library of existing business objects.. :)
Rune Jacobsen
@Rune Jacobsen: We're dealing with the same growing pains at our shop too.
sixlettervariables
A: 
Pieter Breed
A: 

This does only work for public implemented interfaces not for explicite implemented!!!

Roman
A: 

In order to bind to explicit implemented interface members, all you need to do is to use the parentheses. For example:

implicit: {Binding Path=MyValue}

explicit: {Binding Path=(mynamespacealias:IMyInterface.MyValue)}

dummyboy
A: 
{Binding Path=(mynamespacealias:IMyInterface.MyValue)}

This works perfectly. How would you do that with the interface that has generics? Lets say that the class implements the following interface:

public interface IEntity<T>
{
    T Id { get; set; }
}

what would the syntax be in XAML then?

thanks

tridy