wpf - ListView 文本换行而不指定宽度

标签 wpf listview word-wrap

所以我有一个非常基本的 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();
    }
}

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

关于wpf - ListView 文本换行而不指定宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9568823/

相关文章:

c# - 绑定(bind)到模型或 View 模型

listview - 如何在 jQuery-Mobile 中对 ListView 进行分页?

android - 如何动态添加按钮和总计?

javascript - 我可以在 JavaScript 中使用浏览器的自动换行吗?

extjs - Ext JS 中的自动换行网格单元格

c# - 我怎样才能成为更好的 WPF 开发人员?

c# - 依赖注入(inject)和 Entity Framework

css - wordwrap 一个很长的字符串

c++ - 让 C++ 和 WPF 应用程序进行通信的好方法是什么

.net - 如何隐藏 WPF ListView 的 header ?