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

Ray*_*Ray 23 .net wpf listview

如何使控件在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>
Run Code Online (Sandbox Code Playgroud)

编辑抱歉我更改了问题,因为我已将用户控件排除在问题的根源之外.它发生在任何控制.

Ray*_*Ray 64

在缩小我的问题之后,我即将到谷歌并在这里找到答案.

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

<Style TargetType="ListViewItem">
    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
Run Code Online (Sandbox Code Playgroud)

遗憾的是,这会影响每一列,但您可以将其他列的内容设置为左,右,中心,如链接中所述.


Pet*_*ete 6

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

Width="{Binding  RelativeSource={RelativeSource Mode=FindAncestor , AncestorType=ListViewItem, AncestorLevel=1},Path=ActualWidth}">
Run Code Online (Sandbox Code Playgroud)

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

这是执行此操作的示例 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>
Run Code Online (Sandbox Code Playgroud)