所以我有一个非常基本的 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/