Search code examples
wpfgridviewcolumn

Set multiple TextBlock inside a GridViewColumn


I'm trying to set two TextBlock inside a GridViewColumn:

<GridViewColumn.CellTemplate>
  <DataTemplate>
    <TextBlock TextWrapping="Wrap" Text="{Binding PlayerA}" />
    <TextBlock TextWrapping="Wrap" />
  </DataTemplate>
</GridViewColumn.CellTemplate>

but I get that the content is already set, why?


Solution

  • The DataTemplate property can have only ONE child. You are setting TWO children, the two TextBoxes.

    You must include the TextBoxes in a common container.

    If you want a simple horizontal concatenation, you can write this:

    <GridViewColumn.CellTemplate>
      <DataTemplate>
        <StackPanel Orientation="Horizontal">
          <TextBlock Text="blabla1"/>
          <TextBlock Text="blabla2"/>
        </StackPanel>
      </DataTemplate>
    </GridViewColumn.CellTemplate>
    

    If you want an equal distribution of the Width among the two TextBoxes, you can write this:

    <GridViewColumn.CellTemplate>
      <DataTemplate>
        <Grid>
          <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="*"/>
          </Grid.ColumnDefinitions>
          <TextBlock Grid.Column="0" Text="1"/>
          <TextBlock Grid.Column="1" Text="2"/>
        </Grid>
      </DataTemplate>
    </GridViewColumn.CellTemplate>
    

    There are many WPF containers, it depends on what layout you want to achieve, but the rule is: DataTemplate must contain only ONE element.