GridViewColumnHeader不跨越整个ListView宽度

时间:2018-11-15 08:47:41

标签: wpf xaml listview gridview columnheader

我在WPF项目中遇到ListView / GridView组合的布局问题。列标题只是不跨越父ListView的整个宽度。我试图在各处找到文档,但是没有找到有关基础容器/控件模板的任何线索。

我猜标题的标准控件模板包含一些我不关心的东西,我只是无法将其包裹住。

(简化的)ListView在包含标头的行的左侧和右侧有一些像素空间,在此可见父ListView的背景:

https://i.imgur.com/XijV88a.jpg

问题:如何使列标题跨过ListView的整个宽度并使几个像素空间消失?

我的XAML:

<ListView Padding="0"
          BorderThickness="0"
          Background="Red">

    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Setter Property="Background" Value="LightGray" />
            <Setter Property="Margin" Value="0" />
            <Setter Property="Padding" Value="0" />
            <Setter Property="BorderThickness" Value="0" />
        </Style>
    </ListView.ItemContainerStyle>

    <ListView.View>
        <GridView>
            <GridView.ColumnHeaderContainerStyle>
                <Style TargetType="{x:Type GridViewColumnHeader}">
                    <Setter Property="Foreground" Value="White" />
                    <Setter Property="Background" Value="Black" />
                    <Setter Property="BorderThickness" Value="0" />
                    <Setter Property="Margin" Value="0" />
                    <Setter Property="Padding" Value="0" />
                    <Setter Property="HorizontalAlignment" Value="Stretch" />
                </Style>
            </GridView.ColumnHeaderContainerStyle>

            <GridViewColumn Header="1" Width="40"/>
            <GridViewColumn Header="2" Width="40"/>
            <GridViewColumn Header="3" Width="40"/>

        </GridView>
    </ListView.View>

    <ListViewItem> 1 </ListViewItem>
    <ListViewItem> 2 </ListViewItem>
</ListView>

到目前为止,实现我想要的外观的唯一方法是将listview的背景更改为与标题相同的颜色-不过,必须有更好的方法。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

此列不支持将“ *”作为宽度参数,因此您不能轻易地说出-填充其余部分...

您应该做的是挂接到ListView的SizeChanged事件,然后进行计算。因此,例如,在您的情况下,如果我们希望前两列各取40,而第三列取其余,您可以这样做:

private void ListView_SizeChanged(object sender, SizeChangedEventArgs e)
{
    ListView listView = sender as ListView;
    GridView gView = listView.View as GridView;

    var workingWidth = listView.ActualWidth - SystemParameters.VerticalScrollBarWidth;

    gView.Columns[0].Width = 40;
    gView.Columns[1].Width = 40;
    gView.Columns[2].Width = workingWidth - 80;
}

编辑

对于标题行中的间隙(左侧和右侧),您需要像这样更改ColumnHeaderContainerStyle:

<GridView.ColumnHeaderContainerStyle>
    <Style TargetType="{x:Type GridViewColumnHeader}">
        <Setter Property="Foreground" Value="White" />
        <Setter Property="Background" Value="Black" />
        <Setter Property="BorderThickness" Value="0" />
        <Setter Property="Margin" Value="-2,0,-2,0" />
        <Setter Property="Padding" Value="0" />
        <Setter Property="HorizontalAlignment" Value="Stretch" />
    </Style>
</GridView.ColumnHeaderContainerStyle>

因此,请确保只将每边的空白减少2。

相关问题