Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get reference to my WPF ListBox's ScrollViewer?

How can I get a reference to my ListBox's ScrollViewer in C#? I've tried pretty much everything I can think of. The ListBox is in a WPF custom control so we use Template.FindName to get references to all our controls. My ListBox looks like this:

<ListBox
 x:Name="PART_SoundList" 
 ScrollViewer.CanContentScroll="False" 
 ScrollViewer.HorizontalScrollBarVisibility="Auto"  
 ScrollViewer.VerticalScrollBarVisibility="Hidden"
 Focusable="False"
 FocusVisualStyle="{x:Null}"
 HorizontalAlignment="Center"
 VerticalAlignment="Bottom"
 BorderThickness="0" 
 ItemContainerStyleSelector="{StaticResource ListBoxItemAlternatingStyleSelector}"
 ItemsSource="{Binding}">

    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel Orientation="Vertical" Height="850" Focusable="False" Panel.ZIndex="999"  >
                <WrapPanel.RenderTransform>
                        <TransformGroup>
                            <ScaleTransform CenterX="0" CenterY="0" ScaleX=".75" ScaleY=".57" />
                        </TransformGroup>
                    </WrapPanel.RenderTransform>
            </WrapPanel>
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>

    <ListBox.Template>
        <ControlTemplate>
            <ScrollViewer x:Name="Scroller" VerticalAlignment="Bottom" Focusable="False" Style="{StaticResource HorizontalScroller}"   >
                <ItemsPresenter SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" Focusable="False" Panel.ZIndex="999"  />
            </ScrollViewer>
        </ControlTemplate>
    </ListBox.Template>

</ListBox>

Template.FindName("Scroller", this) as ScrollViewer results in null.

Any ideas?

like image 486
Brent Lamborn Avatar asked Oct 31 '25 11:10

Brent Lamborn


1 Answers

You probably try to get a reference to the ScrollViewer too soon. Try to move your code in the loaded event and check if it still returns null:

in your customControl/form constructor:

this.Loaded += MainWindow_Loaded;

void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
   var x = PART_SoundList.Template.FindName("Scroller", PART_SoundList);
}
like image 93
Claudiu Mihaila Avatar answered Nov 03 '25 02:11

Claudiu Mihaila