I'm looking to set the background of a column in a WPF GridView. Many Google results have pointed towards setting the GridViewColumn.CellTemplate to change the appearance of a column. However, I'm met with an issue when setting the background color; it's not stretching to fill the cell:
Here's the xaml I'm working with:
<Window x:Class="ScratchPadWpf.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Width="300" Height="300">
<Grid>
<ListView ItemsSource="{Binding}">
<ListView.View>
<GridView>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid Background="Red">
<TextBlock Text="{Binding FirstName}"/>
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
<GridViewColumn>
<GridViewColumn.CellTemplate>
<DataTemplate>
<Grid Background="Yellow">
<TextBlock Text="{Binding LastName}"/>
</Grid>
</DataTemplate>
</GridViewColumn.CellTemplate>
</GridViewColumn>
</GridView>
</ListView.View>
</ListView>
</Grid>
</Window>
And the xaml.cs for good measure:
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
DataContext = new[]
{
new {FirstName = "Jim", LastName = "Bob"},
new {FirstName = "Frank", LastName = "Smith"},
new {FirstName = "Tooth", LastName = "Paste"},
};
}
}
Setting the DataTemplate's Grid's width and height to be larger than the cell with a negative margin can produce a close result, but if you resize the column, the problem shows itself again.
<Grid Background="Yellow" Height="22" Width="50" Margin="-6">
Is there a way to fill the cell with color?
Set the HorizontalContentAlignment
of the ItemContainerStyle
:
<ListView ItemsSource="{Binding}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
Result:
Digging up an old thread, but I found a dodgy fix for this
<Grid Background="{Binding backGround}" Margin="-6,0,-6,0">
<TextBlock Margin="6,0,6,0" Text="{Binding myText}" TextAlignment="Right" />
</Grid>
Moves the margins so the background color fills the entire cell, but then moves them back so the text is still in the right spot. Works for now until it's fixed properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With