Wpf 不指定宽度的ListView文本换行

Wpf 不指定宽度的ListView文本换行,wpf,listview,word-wrap,Wpf,Listview,Word Wrap,我有一个非常基本的ListView,它有两列。示例代码如下: <ListView Margin="0,0,0,10" x:Name="lvOpenItems" ItemsSource="{Binding Path=OpenItems}" ScrollViewer.HorizontalScrollBarVisibility="Disabled"> <ListView.View> <GridView> <Gri

我有一个非常基本的ListView,它有两列。示例代码如下:

<ListView Margin="0,0,0,10" x:Name="lvOpenItems" ItemsSource="{Binding Path=OpenItems}" ScrollViewer.HorizontalScrollBarVisibility="Disabled">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="DispenserId" DisplayMemberBinding="{Binding Path=DispenserId}" Width="100"/>
            <GridViewColumn Header="ProductName" x:Name="pName" Width="200">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock TextWrapping="Wrap" Text="{Binding Path=ProductName}" />
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

现在,ProductName字段有时会变得有点长,因此需要包装。以上代码工作正常;文本换行。但是,我想知道是否可以在不指定宽度的情况下以某种方式启用文本换行。现在,如果用户调整窗口的大小,我的列将停留在200。理想情况下,我希望ProductName占用所有剩余空间,然后相应地包装

可以这样做吗?

在ListView集合上

  VerticalAlignment="Stretch"
然后在柱上使用转换器

  GridViewColumn Width="{Binding ElementName=lvOpenItems, Path=ActualWidth, Converter={StaticResource widthConverter}, ConverterParameter=100}"



[ValueConversion(typeof(double), typeof(double))]
public class WidthConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // value is the total width available
        double otherWidth;
        try
        {
            otherWidth = System.Convert.ToDouble(parameter);
        }
        catch
        {
            otherWidth = 100;
        }
        if (otherWidth < 0) otherWidth = 0;

        double width = (double)value - otherWidth;
        if (width < 0) width = 0;
        return width; // columnsCount;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
GridViewColumn Width=“{Binding ElementName=lvOpenItems,Path=ActualWidth,Converter={StaticResource widthConverter},ConverterParameter=100}”
[值转换(typeof(double),typeof(double))]
公共类宽度转换器:IValueConverter
{
公共对象转换(对象值、类型targetType、对象参数、CultureInfo区域性)
{
//值是可用的总宽度
双倍宽度;
尝试
{
otherWidth=System.Convert.ToDouble(参数);
}
抓住
{
其他宽度=100;
}
如果(otherWidth<0)otherWidth=0;
双宽度=(双)值-其他宽度;
如果(宽度<0)宽度=0;
返回宽度;//columnsCount;
}
公共对象转换回(对象值、类型targetType、对象参数、CultureInfo区域性)
{
抛出新的NotImplementedException();
}
}

是,该参数是可重用的。您还需要考虑垂直滚动条

是否尝试将文本块包装到网格中?它可能会起作用。有没有一种方法可以使用网格来保持列标题?请注意ConverterParameter为100,并且绑定到lvOpenItems的实际宽度(您的ListView)。100是另一个GridViewColumn的宽度,所以我猜他的转换器只是从宽度中减去100。一种很好的获得所需大小的干净方法。我还有另一个要模拟*的方法,参数是column count。GridView有点粗糙,但速度很快。