Winrt - ListView项目不会垂直填充所有空格

时间:2014-10-29 21:29:16

标签: wpf listview windows-runtime winrt-xaml listviewitem

我有以下listView:

 <ListView x:Name="sportList" Grid.Row="0" Grid.Column="0" SelectionChanged="sportList_SelectionChanged">
     <ListView.ItemContainerStyle>
         <Style TargetType="ListViewItem">
             <Setter Property="HorizontalContentAlignment" Value="Stretch" />                        
         </Style>
     </ListView.ItemContainerStyle>
     <ListView.ItemTemplate>
         <DataTemplate>
             <TextBlock Text="{Binding}" Margin="15,0,0,0" />
         </DataTemplate>
     </ListView.ItemTemplate>
 </ListView>

它产生以下Listview控件:

enter image description here

我想垂直拉伸listviewitems,按顺序填充所有空白区域。 与此类似的东西(达到指定文本块的固定高度)

enter image description here

1 个答案:

答案 0 :(得分:1)

您必须将Height {或MinHeight} ListViewItem绑定到ListView的ActualHeight。当然,我们需要一个转换器将每个项目的ActualHeight转换为相等的高度:

<ListView x:Name="sportList" Grid.Row="0" Grid.Column="0"
          ScrollViewer.VerticalScrollBarVisibility="Disabled" 
          ScrollViewer.CanContentScroll="False" UseLayoutRounding="True">
    <ListView.Resource> 
       <local:AutoFillHeightConverter x:Key="hc"/>
    </ListView.Resource>
    <ListView.ItemContainerStyle>
      <Style TargetType="ListViewItem">
         <Setter Property="HorizontalContentAlignment" Value="Stretch" />
         <Setter Property="MinHeight" Value="{Binding ActualHeight, 
                 RelativeSource={RelativeSource AncestorType=ListView}, 
              Converter={StaticResource hc}, ConverterParameter=win@sportList}"/>
      </Style>
    </ListView.ItemContainerStyle>
    <ListView.ItemTemplate>
      <DataTemplate>
         <TextBlock Text="{Binding}" Margin="15,0,0,0" />
      </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

请注意,您的要求意味着我们不需要垂直的ScrollBar。所以我们最好禁用或隐藏它。同时将CanContentScroll设置为false,将UseLayoutRounding设置为true,以便更好地(更精确地设置高度)渲染。

以下是AutoFillHeightConverter类(我们在ListView的资源中嵌入了一个实例):

public class AutoFillHeightConverter : IValueConverter {
    object IValueConverter.Convert(object value, Type targetType, object parameter,
                                   System.Globalization.CultureInfo culture)
    {
        var p = parameter as string;
        var win = Application.Current.Windows.Cast<Window>()
                             .First(w => w.Name == p.Split('@')[0]);
        var lv = win.FindName(p.Split('@')[1]) as ListView;
        var lvh = Convert.ToDouble(value);            
        return lv.Items.Count == 0 ? Binding.DoNothing : (lvh / lv.Items.Count);
    }

    object IValueConverter.ConvertBack(object value, Type targetType, 
                       object parameter, System.Globalization.CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}    

注意绑定的ConverterParameter,我们将其设置为字符串。该字符串包含由@分隔的2个部分。第一部分应该是Window Name,第二部分应该是ListView&#39; s Name。我们需要这些Name来访问Convert方法中的ListView实例来转换高度。