如何在WPF ContentControl中找到ScrollViewer?

时间:2015-03-19 02:00:54

标签: wpf wpf-controls

WPF 4.5 / C#

我有一个应用程序,我有几个WPF Windows,每个都使用这个自定义内容控件。我在XAML中使用它像这样:

<ContentControl Name="myControl" Style="{StaticResource ReservedSpaceScrollBar}"

在后面的代码中,我需要能够访问里面的ScrollViewer,所以我可以调用.ScrollToTop()

我试过这个,但它不起作用:

((的ScrollViewer)this.myControl.FindName( “滚动”))ScrollToTop();

...但.FindName找不到ScrollViewer。我究竟做错了什么?如何使这项工作?

风格的XAML低于......

   <Style TargetType="{x:Type ContentControl}" x:Key="ReservedSpaceScrollBar">
      <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
      <Setter Property="Template">
         <Setter.Value>
            <ControlTemplate TargetType="{x:Type ContentControl}">
               <ScrollViewer PanningMode="Both" VerticalScrollBarVisibility="Auto" x:Name="Scroll" FocusVisualStyle="{x:Null}">
                  <Grid>
                     <Grid.ColumnDefinitions>
                        <ColumnDefinition />
                        <ColumnDefinition Width="Auto" />
                     </Grid.ColumnDefinitions>
                     <ContentPresenter />
                     <Border Width="{x:Static SystemParameters.VerticalScrollBarWidth}" x:Name="Placeholder" Grid.Column="1" />
                  </Grid>
               </ScrollViewer>
               <ControlTemplate.Triggers>
                  <DataTrigger Binding="{Binding ComputedVerticalScrollBarVisibility, ElementName=Scroll}" Value="Visible">
                     <Setter TargetName="Placeholder" Property="Visibility" Value="Collapsed" />
                  </DataTrigger>
               </ControlTemplate.Triggers>
            </ControlTemplate>
         </Setter.Value>
      </Setter>
   </Style>

1 个答案:

答案 0 :(得分:1)

查看VisualTreeHelper

使用该课程,你可以看到元素的孩子;例如:

var childCount = VisualTreeHelper.GetChildrenCount(this.myControl);

for (int i = 0; i < childCount; i++)
{
    var child = VisualTreeHelper.GetChild(this.myControl, i);

    if (child.GetValue(NameProperty).ToString() == "Scroll")
    {
        ((ScrollViewer)child).ScrollToTop();
    }
}