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

Wpf 如何绑定到ListView的首选大小?,wpf,listview,scrollview,Wpf,Listview,Scrollview,我有一个WPFListView,应该用一个始终可见的页脚扩展它。 页脚的行为应类似于页眉,且不应滚动。 以下XAML使用链接到代码隐藏的外部ScrollViewer来控制ListView的ScrollViewer: <Window x:Class="LayoutTests.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://

我有一个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>
GetScrollViewer()
的定义如下(但并不重要):

公共静态DependencyObject GetScrollViewer(DependencyObject depObj) { 如果(depObj是ScrollViewer) {返回depObj;} for(int i=0;i
ListView
ScrollViewer
显然知道其子对象的首选宽度。 问题是我找不到一种方法来绑定到那个宽度。这就是:

如何将
矩形.Width
绑定到
列表视图的首选大小


或者,如何在
列表视图
中包含始终可见的页脚?

您需要绑定到
滚动查看器
extendwidth
。根据,它是一个
依赖属性
。请注意,您需要的是
列表视图的
滚动查看器
,而不是在列表视图下方创建的附加查看器

您可以使用
GetScrollViewer
函数在
ListView
上查找
ScrollViewer
。当然,您需要在代码隐藏中设置绑定。诸如此类:

Binding b = new Binding("ExtentWidth") { Source = GetScrollViewer(L) };
rect.SetBinding(Rectangle.WidthProperty, b);

您的绑定设置非常有趣-我不知道通过在{}中指定代码可以搞乱它的内容。那有名字吗?目前它对我不起作用-滚动条没有出现。正在调试。奇怪——它的宽度是多少?(您可以使用进行查找)。嗯,您可以通过指定虚拟转换器(并在其
Convert
方法中设置断点)来调试绑定。“ViewportWidth”绑定到显示的内容宽度。我想要的是“延伸宽度”。在绑定中设置该选项可以使上述答案生效@Vlad如果你改变答案,我会把它标记为解决方案。
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;
}
Binding b = new Binding("ExtentWidth") { Source = GetScrollViewer(L) };
rect.SetBinding(Rectangle.WidthProperty, b);