【问题标题】:ListView Text Wrapping Without Specifying Width不指定宽度的 ListView 文本换行
【发布时间】:2012-03-23 01:16:45
【问题描述】:

所以我有一个非常基本的 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 占用所有剩余空间,然后相应地换行。

可以这样做吗?

【问题讨论】:

  • 尝试将 TextBlock 包装在网格中?它可能会起作用。
  • 有没有办法使用网格来保留列标题?

标签: wpf listview word-wrap


【解决方案1】:

在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();
    }
}

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

【讨论】:

  • 注意 ConverterParameter 为 100,并且绑定到 lvOpenItems(您的 ListView)的 ActualWidth。 100 是另一个 GridViewColumn 的宽度,所以我猜他的转换器只是从宽度中减去 100。一种获得所需尺寸的好方法。
  • 我还有一个用列数参数来模拟*。 GridView 有点原始,但速度很快。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
  • 2013-10-08
  • 2012-05-24
  • 2011-09-14
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多