在WPF中拉伸控件以填充ListView列

问题描述 投票:0回答:3

如何使控件填充 ListView(使用 GridView)中的整个单元格?我尝试过各种属性,但控件始终是最小尺寸。

这是我的xaml。

<Window x:Class="ListViewUserControlTest.Window1"
  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  xmlns:local="clr-namespace:ListViewUserControlTest"
  Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <DataTemplate x:Key="UserControlCell">
            <Rectangle Fill="Red" HorizontalAlignment="Stretch" MinWidth="10" MinHeight="10" />              
        </DataTemplate>
    </Window.Resources>
    <Grid>        
        <ListView Name="MyListView">
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="30" Header="Col1" DisplayMemberBinding="{Binding Name}"  />
                    <GridViewColumn Width="200" Header="Col2" CellTemplate="{StaticResource UserControlCell}"  />
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>

编辑 抱歉,我更改了问题,因为我已经消除了作为问题根源的用户控件。任何控制都会发生这种情况。

.net wpf listview
3个回答
79
投票

缩小我的问题范围后,我准备去谷歌并找到答案

基本上由于某种原因,ListViewItems 设置为左对齐。将它们设置为“拉伸”可解决此问题。这是通过这样的风格完成的:

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

不幸的是,这会影响每一列,但您可以按照链接中的说明将其他列的内容设置为左、右、居中。


6
投票

另一个几乎解决方案是在进入 gridview 列的数据模板中执行以下操作

Width="{Binding  RelativeSource={RelativeSource Mode=FindAncestor , AncestorType=ListViewItem, AncestorLevel=1},Path=ActualWidth}">

这会导致文本框拉伸到列的宽度,但右边缘被剪裁并且不渲染。我还没有修复那部分。所以已经接受的答案可能仍然是最好的答案。

这是一个执行此操作的示例 DataTemplate。

<DataTemplate DataType="{x:Type local:EditableStringElement}"
          x:Key="cellSalutation">
<TextBox Text="{Binding _RecipientData._Salutation.Value , Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
         IsEnabled="{Binding _RecipientData._Salutation.IsEnabled}"
         Width="{Binding  RelativeSource={RelativeSource Mode=FindAncestor , AncestorType=ListViewItem, AncestorLevel=1},Path=ActualWidth}">
</TextBox>


3
投票

您的用户控件指定“高度”和“宽度”属性的值。不允许任何内容覆盖您已明确设置的属性。删除“高度”和“宽度”,控件的容器将能够扰乱尺寸。

您可能需要设置合理的“MinHeight”和“MinWidth”以防止容器压扁您。

不同的容器对控件的大小执行不同的操作;例如,Grid 将您展开以填充您所在的网格单元,而 StackPanel 将您缩小到最小尺寸。所以你可能也需要处理这个问题。

© www.soinside.com 2019 - 2024. All rights reserved.