How do I bind to the preferred size of a ListView?

2019-06-11 03:46发布

问题:

I have a WPF ListView that should be extended with an always visible footer. The footer shall behave like a header and should not be scrolled away. The following XAML uses an external ScrollViewer linked to code behind to steer the ScrollViewer of the ListView:

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

In the code behind this looks like this:

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() is defined like this (but unimportant):

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

The ScrollViewer of ListView obviously knows about the preferred width of its children. The problem is that I cant find a way to bind to that width. So here it is:

How do I bind Rectangle.Width to the preferred size of the ListView?

Or, alternatively, how do I include a footer in the ListView that is always visible?

回答1:

You need to bind against ExtentWidth of your ScrollViewer. According to http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.extentwidth.aspx, it's a DependencyProperty. Mind that you need the ScrollViewer of your ListView, not the additional one you are creating below the list view.

You can use your GetScrollViewer function to find the ScrollViewer on the ListView. Of course, you'll need to set the binding in the code-behind. Something like that:

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