如何绑定到ListView的首选大小?

时间:2012-03-28 11:58:24

标签: wpf listview scrollview

我有一个WPF ListView,应该使用始终可见的页脚进行扩展。 页脚应该像标题一样,不应滚动。 以下XAML使用链接到代码的外部ScrollViewer来引导ListView的ScrollViewer:

<Window x:Class="LayoutTests.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="125" Width="176">
  <Grid>
    <StackPanel>
      <ListView Name="L" ScrollViewer.HorizontalScrollBarVisibility="Hidden">
        <ListViewItem Content="Brown brownie with a preference for white wheat."/>
        <ListViewItem Content="Red Redish with a taste for oliv olives."/>
      </ListView>
      <ScrollViewer CanContentScroll="False" HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" ScrollChanged="ScrollViewer_ScrollChanged">
        <!-- Would like to bind Rectangle.Width to the preferred width of L -->
        <Rectangle Height="20" Width="500" Fill="Red"/>
      </ScrollViewer>
    </StackPanel>
  </Grid>
</Window>

在后面的代码中看起来像这样:

private void ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
  var bottomScrollViewer = sender as ScrollViewer;
  var listScrollViewer = GetScrollViewer(L) as ScrollViewer;
  if (listScrollViewer != null && bottomScrollViewer != null )
    listScrollViewer.ScrollToHorizontalOffset( bottomScrollViewer.HorizontalOffset );
}

GetScrollViewer()定义如下(但不重要):

public static DependencyObject GetScrollViewer(DependencyObject depObj)
{
  if (depObj is ScrollViewer)
  { return depObj; }
  for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
  {
    var child = VisualTreeHelper.GetChild(depObj, i);
    var result = GetScrollViewer(child);
    if (result == null) { continue; }
    else { return result; }
  }
  return null;
}

ScrollViewer的{​​{1}}显然知道其子女的首选宽度。 问题是我无法找到绑定到该宽度的方法。所以这就是:

如何将ListView绑定到Rectangle.Width的首选大小?

或者,或者,如何在始终可见的ListView中添加页脚?

1 个答案:

答案 0 :(得分:1)

您需要绑定ExtentWidth的{​​{1}}。根据{{​​3}},它是ScrollViewer。请注意,您需要DependencyProperty的{​​{1}},而不是您在列表视图下方创建的其他内容。

您可以使用ScrollViewer功能查找ListView上的GetScrollViewer。当然,您需要在代码隐藏中设置绑定。这样的事情:

ScrollViewer