【问题标题】:How to access ScrollViewer in ItemsControl如何在 ItemsControl 中访问 ScrollViewer
【发布时间】:2013-02-13 14:59:04
【问题描述】:

我正在尝试访问下面 XAML 中名为“ScrollViewerItems”的 ScrollViewer,并在后面的代码中使用它。该名称似乎无法识别,可能是因为它嵌入在 ItemsControl 中。我不需要命名访问,但是如何在后面的代码中访问 ItemsControl 的 ScrollViewer?

<ItemsControl x:Name="EnteredItemsView" ItemsSource="{Binding LineItems}"  VirtualizingStackPanel.IsVirtualizing="True" ScrollViewer.CanContentScroll="True" ScrollViewer.HorizontalScrollBarVisibility="Disabled" ScrollViewer.VerticalScrollBarVisibility="Auto">
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <VirtualizingStackPanel />
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.Template>
        <ControlTemplate>
            <ScrollViewer x:Name="ScrollViewerItems" Focusable="False">
                <ItemsPresenter SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
            </ScrollViewer>
        </ControlTemplate>
    </ItemsControl.Template>
    <ItemsControl.ItemTemplate>
    ...

【问题讨论】:

  • 你可以使用可视化树助手或者可以或者查询templatedchild

标签: wpf itemscontrol scrollviewer


【解决方案1】:

ScrollViewer 是 ItemsControl 的可视子项:

var scrollViewer =
    VisualTreeHelper.GetChild(EnteredItemsView, 0) as ScrollViewer;

请注意,必须先加载 ItemsControl,然后才能访问子项。

您可以将Loaded 处理程序添加到 ItemsControl

<ItemsControl Loaded="ItemsControlLoaded" ...>

您访问 ScrollViewer 的位置

private void ItemsControlLoaded(object sender, EventArgs e)
{
    var itemsControl = sender as DependencyObject;
    var scrollViewer =
        VisualTreeHelper.GetChild(itemsControl, 0) as ScrollViewer;
}

【讨论】:

  • 指定的索引超出范围或索引处的子项为空。如果 VisualChildrenCount 返回零,则不要调用此方法,表示 Visual 没有子级。 EnteredItemsView.VisualChildrenCount 为 0 仅供参考
  • 您在加载 ItemsControl 之前调用了 GetChild!查看我的编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多