问题描述
限时送ChatGPT账号..我希望在 WPF GridView 中设置列的背景.许多 Google 结果都指向设置 GridViewColumn.CellTemplate 以更改列的外观.但是,我在设置背景颜色时遇到了一个问题;它不会拉伸以填充单元格:
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:
这是我正在使用的 xaml:
Here's the xaml I'm working with:
<Window x:Class="ScratchPadWpf.Window1"
xmlns="http://schemas.microsoft/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft/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>
和 xaml.cs 很好的衡量:
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"},
};
}
}
将 DataTemplate 的 Grid 的宽度和高度设置为大于具有负边距的单元格可以产生接近的结果,但是如果您调整列的大小,问题又会再次出现.
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?
推荐答案
设置ItemContainerStyle
的HorizontalContentAlignment
:
<ListView ItemsSource="{Binding}">
<ListView.ItemContainerStyle>
<Style TargetType="ListViewItem">
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
结果:
这篇关于在 WPF ListView/Gridview 中设置列背景的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论