How to bind DataTemplate datatype to interface? How to bind DataTemplate datatype to interface? wpf wpf

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.


It seems that using a DataTemplateSelectoris the way to go in such situations.


I have used Binding with interface types in a data template, in uwp. I did not specify the interface type explicitly on the Binding path. It worked when the interface was not implemented explicitly. When the interface was implemented explicitly it failed silently. I believe that if the interface is implemented explicitly then the explicit reference to the interface type in the Binding path is needed, so that the Binding can correctly look up the property path.