【问题标题】:How do I bind to the preferred size of a ListView?如何绑定到 ListView 的首选大小?
【发布时间】:2012-04-12 00:23:15
【问题描述】:

我有一个 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;
}

ListViewScrollViewer 显然知道其子项的首选宽度。 问题是我找不到绑定到那个宽度的方法。所以这里是:

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

或者,或者,我如何在ListView 中包含始终可见的页脚?

【问题讨论】:

    标签: wpf listview scrollview


    【解决方案1】:

    您需要绑定ExtentWidthScrollViewer。根据http://msdn.microsoft.com/en-us/library/system.windows.controls.scrollviewer.extentwidth.aspx,它是DependencyProperty。请注意,您需要的是 ListView 中的 ScrollViewer,而不是您在列表视图下方创建的另一个。

    您可以使用GetScrollViewer 函数在ListView 上找到ScrollViewer。当然,您需要在代码隐藏中设置绑定。类似的东西:

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

    【讨论】:

    • 您的绑定设置非常有趣 - 我不知道可以通过在 {} 中指定代码来弄乱它的内容。有那个名字吗?目前它对我不起作用 - 滚动条没有出现。正在调试中。
    • 奇怪——它的宽度是多少? (您可以使用Snoop utility 查找)。
    • 好吧,您可以通过指定一个虚拟转换器(并在其Convert 方法中设置断点)来调试绑定。
    • googleable 名称应该是“在代码隐藏中设置绑定”
    • “ViewportWidth”绑定到内容的显示宽度。我在这里想要的是“ExtentWidth”。在绑定中设置它可以使上述答案起作用。 @Vlad 如果您更改答案,我将其标记为解决方案。
    猜你喜欢
    • 2017-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-14
    • 1970-01-01
    • 2012-02-07
    • 1970-01-01
    • 2013-09-07
    相关资源
    最近更新 更多