2

So I've got a pretty basic ListView, that has two columns. Sample code below:

<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>

Now, the ProductName field can sometimes get a little long, so it needs to wrap. The above code works OK; the text wraps. However, I'm wondering if its possible to somehow get text wrapping enabled without having to specify the widths. Right now, if the user resizes the window, my column is stuck at 200. Ideally, what I'd want is to have the ProductName take up all the remaining space, and then wrap accordingly.

Is it possible to do this?

H.B.
  • 166,899
  • 29
  • 327
  • 400
Jim B
  • 8,344
  • 10
  • 49
  • 77

1 Answers1

2

On the ListView set

  VerticalAlignment="Stretch"

Then use a converter on the column

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

Yes the parameter is so you can reuse. You also need to account for vertical scroll bar.

paparazzo
  • 44,497
  • 23
  • 105
  • 176
  • Note the ConverterParameter of 100, and the binding being to the ActualWidth of lvOpenItems (your ListView). 100 is the width of the other GridViewColumn, so my guess would be that his converter just substracts 100 from the width. A nice clean way of getting the size you want. – ianschol Mar 05 '12 at 15:54
  • And I have another to simulate * with a parameter of column count. GridView is a little raw but it is fast. – paparazzo Mar 05 '12 at 16:06