Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

xaml - Setting Column Background in WPF ListView/Gridview

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:

Ugly Grid View

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">

Still Ugly

Is there a way to fill the cell with color?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Set the HorizontalContentAlignment of the ItemContainerStyle:

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

Result:

alt text


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...