2
votes

I'm using a CellTemplateSelector to change the cell background color of specific cells with specific values. However, I can't get the cell background color to fill the cell; it hugs the content. Here's my markup:

<DataTemplate x:Key="Template1">
  <Grid Background="#C0D9AF">
    <TextBlock Text="{Binding Path=Value}" />
  </Grid>
</DataTemplate>

<DataTemplate x:Key="Template2">
  <Grid Background="#FFFCCF">
    <TextBlock Text="{Binding Path=Value}" />
  </Grid>
</DataTemplate>

And my code:

private class CellTemplateSelector : DataTemplateSelector
{
  public override DataTemplate SelectTemplate(object item,
                                              DependencyObject container)
  {
    return ((FrameworkElement)container).FindResource(condition 
           ? "Template1"
           : "Template2") as DataTemplate;
  }
}
1

1 Answers

2
votes

Change your templates to use a a read-only TextBox with a Background color, and set HorizontalContentAlignment to Stretch for the ListViewItem:

<DataTemplate x:Key="Template1">
    <Grid>
        <TextBox Text="{Binding Value}"  Background="Crimson" IsReadOnly="True" />
    </Grid>
</DataTemplate>
<DataTemplate x:Key="Template2">
    <Grid>
        <TextBox Text="{Binding Value}" Background="HotPink" IsReadOnly="True" />
    </Grid>
</DataTemplate>


<ListView.ItemContainerStyle>
  <Style TargetType="ListViewItem">
    <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
  </Style>
</ListView.ItemContainerStyle>

You can also take a look at this answer for more information.