Search code examples
c#wpfdatatemplatecontentcontrol

What does it mean: "the ContentControl does not use the DataTemplate automatically."?


I am struggling to get my datatemplate binding to work; I explicitly bind my DataTemplate to a datatype

<DataTemplate DataType="{x:Type local:ExcelReportVM}">
    <local:ExcelReport DoubleClickHandler="{Binding}">
        <local:ExcelReport.RowColorConverter>
            <local:ReportRowColorConverter/>
        </local:ExcelReport.RowColorConverter>
    </local:ExcelReport>
</DataTemplate>

However, I found that even though my control.DataContext is ExcelReportVM, the above DataTemplate is simply not applied.

Then I read in MSDN that

if you are binding a ContentControl to a collection of Task objects, the ContentControl does not use the DataTemplate automatically. This is because the binding on a ContentControl needs more information to distinguish whether you want to bind to an entire collection or the individual objects. If your ContentControl is tracking the selection of an ItemsControl type, you can set the Path property of the ContentControl binding to "/" to indicate that you are interested in the current item. For an example, see How to: Bind to a Collection and Display Information Based on Selection. Otherwise, you need to specify the DataTemplate explicitly by setting the ContentTemplate property.

The explanation sounds very abstract and I have no idea what it is talking about after reading it a few times. Anyone care to explain it with a proper example?


Solution

  • The implicit DataTemplate is applied if you set or bind the Content property of a ContentControl to an instance of an ExcelReportVM object:

    <ContentControl x:Name="control" />
    

    content.Content = new ExcelReportVM();