如何在ItemsControl中访问ScrollViewer

时间:2013-02-13 14:59:05

标签: wpf itemscontrol scrollviewer

我正在尝试在下面的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>
    ...

1 个答案:

答案 0 :(得分:3)

ScrollViewer是ItemsControl的可视子级:

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

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

您可以向ItemsControl

添加Loaded处理程序
<ItemsControl Loaded="ItemsControlLoaded" ...>

您访问ScrollViewer的地方

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