Search code examples
wpfdatatemplatedatagridviewcolumncontentpresenter

WPF GridViewColumn.CellTemplate DataTemplate ContentPresenter


I have a ListView which uses DataTemplates. If i use this in a ListView defined the columns over XAML it works how it schould. My DataTemplates are used in my view. But if i want to use the same DataTemplates in a second ListView, where i add new columns to the ListView it does not use my DataTemplate. What should i Do?

The code in XAML for the first ListView looks like this:

<GridViewColumn x:Name="lvSecondColumn" Header="Value" Width="200">
   <GridViewColumn.CellTemplate>
      <DataTemplate>
        <ContentPresenter Content="{Binding}"/>
      </DataTemplate>
  </GridViewColumn.CellTemplate>
</GridViewColumn>

My Code i use for generating a column in second ListView is:

DataColumn dc = (DataColumn)colum;

GridViewColumn column = new GridViewColumn( );
column.DisplayMemberBinding = new Binding( dc.ColumnName ) );
column.Header = dc.ColumnName;
TestColumns.Columns.Add( column );

TestListView.ItemsSource = dt.DefaultView; 

In WPFInspector i see there is no ContentPresenter in my dynamic Generated Column. Picture from missing ContentPresenter from WPFInspector How to add the ContentPresenter to my dynamic column???


Solution

  • You can't set both Binding and DataTemplate. According to the docs https://msdn.microsoft.com/en-us/library/system.windows.controls.gridviewcolumn.displaymemberbinding(v=vs.110).aspx

    The following properties are all used to define the content and style of a column cell, and are listed here in their order of precedence, from highest to lowest: - DisplayMemberBinding - CellTemplate - CellTemplateSelector

    If you use binding then it will generate a textbox with a ".ToString()" of the bound object. If you are aware of the structure of your items in the ListView you can just make DataTemplates with appropriate bindings in it. However when generating columns dynamically this is an issue.

    You can dynamically generate a datatemplate for your column and integrate the binding in it:

    public DataTemplate CreateColumnTemplate(string property)
    {
        StringReader stringReader = new StringReader(
        @"<DataTemplate 
            xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> 
                <ContentPresenter Content=""{Binding " + property + @"}""/> 
            </DataTemplate>");
        XmlReader xmlReader = XmlReader.Create(stringReader);
        return XamlReader.Load(xmlReader) as DataTemplate;
    }
    

    Then you can generate your columns like this:

    GridViewColumn column = new GridViewColumn( );
    column.CellTemplate = CreateColumnTemplate(dc.ColumnName);
    column.Header = dc.ColumnName;
    TestColumns.Columns.Add( column );
    

    I didn't run the code there may be little mistakes.