You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Border拉伸填满ListViewItem的整个宽度

WPF ListView项模板内元素占满整行宽度配置方法

问题复现代码

<ListView ItemsSource="{Binding SerialNumbers}" SelectionMode="Multiple" HorizontalAlignment="Stretch">
    <ListView.ItemTemplate>
        <DataTemplate>
            <Border Background="Red" Padding="14 5" HorizontalAlignment="Stretch">
                <TextBlock HorizontalAlignment="Stretch" Text="{Binding Number}" />
                <behaviours:Interaction.Triggers>
                    <behaviours:EventTrigger EventName="MouseLeftButtonUp">
                        <behaviours:InvokeCommandAction Command="{Binding Path=DataContext.SerialNumberSelectedCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{Binding}" />
                    </behaviours:EventTrigger>
                </behaviours:Interaction.Triggers>
            </Border>
         </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

上述代码中,即使给ListView、Border、TextBlock都设置了HorizontalAlignment="Stretch",Border仍然无法占满ListViewItem的全宽,仅点击红色区域能触发绑定的MouseLeftButtonUp命令,行内空白区域点击无响应。
Border未拉伸的运行效果

修复方法

问题出在ListView默认生成的ListViewItem容器,默认HorizontalContentAlignment属性值不是Stretch,导致内容容器不会给子元素分配全宽空间。只需给ListView添加ItemContainerStyle显式设置该属性即可:

<ListView ItemsSource="{Binding SerialNumbers}" SelectionMode="Multiple" HorizontalAlignment="Stretch">
    <!-- 新增项容器样式配置 -->
    <ListView.ItemContainerStyle>
        <Style TargetType="ListViewItem">
            <Setter Property="HorizontalContentAlignment" Value="Stretch"/>
        </Style>
    </ListView.ItemContainerStyle>
    
    <ListView.ItemTemplate>
        <DataTemplate>
            <Border Background="Red" Padding="14 5" HorizontalAlignment="Stretch">
                <TextBlock HorizontalAlignment="Stretch" Text="{Binding Number}" />
                <behaviours:Interaction.Triggers>
                    <behaviours:EventTrigger EventName="MouseLeftButtonUp">
                        <behaviours:InvokeCommandAction Command="{Binding Path=DataContext.SerialNumberSelectedCommand, RelativeSource={RelativeSource AncestorType=UserControl}}" CommandParameter="{Binding}" />
                    </behaviours:EventTrigger>
                </behaviours:Interaction.Triggers>
            </Border>
         </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

配置完成后Border会自动拉伸占满整行宽度,点击ListViewItem任意位置都会触发绑定的选中命令。

可选优化:如果需要全局生效,可以将该ListViewItem样式放到应用级资源字典中,无需每个ListView单独配置。

内容的提问来源于stack exchange,提问作者Eddie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 19:57:27