Wednesday, May 18, 2011

Silverlight / WPF: Is it possible to bind to an explicit interface indexer implementation?

The WPF binding system allows you to bind to Indexers and properties and it also have a nice feature that allows you to bind to the explicit implementation of interfaces’ members, allowing you to resolve possible ambiguities if the properties have the same names, let’s consider this simple example you have the following two interfaces and a class that implements them:

public interface IFirst
{
   string this[string index] { get; }
   String Name { get; }
}
public interface ISecond
{
   string this[string index] { get; }
   String Name { get; }
}
public class Entity : IFirst, ISecond
{
   public string Name
   {
       get { return "Class Name"; }
   }
   
   public string this[string index]
   {
       get { return "Class Indexer"; }
   }

And you can bind them with a syntax like this:

<stackpanel>
   <textbox text="{Binding Path=Name, Mode=OneWay}">
   <textbox text="{Binding Path=(local:IFirst.Name), Mode=OneWay}">
   <textbox text="{Binding Path=(local:ISecond.Name), Mode=OneWay}">
   <textbox text="{Binding Path=[0], Mode=OneWay}">
   <!--binding attempt 1 -->
   <textbox text="{Binding Path=(local:IFirst)[0], Mode=OneWay}">
   <textbox text="{Binding Path=(local:ISecond)[0], Mode=OneWay}">
   <!--binding attempt 2 -->
   <textbox text="{Binding Path=(local:IFirst.Item)[0], Mode=OneWay}">
   <textbox text="{Binding Path=(local:ISecond.Item)[0], Mode=OneWay}">
</textbox></textbox></textbox></textbox></textbox></textbox></textbox></textbox></stackpanel>

....

Silverlight currently does not support binding to explicit interface implementations: when you try to write something similar to that the Xaml parser give you the E_UNEXPECTED error. I think this is one of the reasons why the Silverlight Team introduced a new interface for validation and error reporting like INotifyDataErrorInfo instead of just relying on the IDataErrorInfo typical to WPF: the IDataErrorInfo indexer (used to access the error’s collection) most of the time it’s implemented using explicit interface implementation; I would really like to see a porting of that interface in WPF soon cause I think it has a better design than the current IDataErrorInfo.

Read more: Windows Phone 7