How to bind DataTemplate datatype to interface?

You can bind to interfaces by telling wpf explicitly that you are binding to an interface field:

(Please note that ViewModelBase is simply a base-class that implements the INotifyPropertyChanged interface)

public class Implementation : ViewModelBase, IInterface
{
    private string textField;

    public string TextField
    {
        get
        {
            return textField;
        }
        set
        {
            if (value == textField) return;
            textField = value;
            OnPropertyChanged();
        }
    }
}

public interface IInterface
{
    string TextField { get; set; }
}

Then on the ViewModel:

private IInterface interfaceContent;
public IInterface InterfaceContent
{
    get { return interfaceContent; }
}

And finally the Xaml that makes it possible:

<ContentControl Grid.Row="1" Grid.Column="0" Content="{Binding InterfaceContent}">
    <ContentControl.ContentTemplate>
        <DataTemplate DataType="{x:Type viewModels:IInterface}">
            <TextBox Text="{Binding Path=(viewModels:IInterface.TextField)}"/>
        </DataTemplate>
    </ContentControl.ContentTemplate>
</ContentControl>

As you can see, the binding refers explicitly to the ‘IInterface’ definiton.

Leave a Comment

tech