获取对C#中WPF ListBox的ScrollViewer的引用? [英] Get reference to my WPF ListBox's ScrollViewer in C#?
问题描述
我认为这应该很容易,但是我很难过.
I think this should be easy but I'm having a tough time with it.
如何在C#中获得对ListBox的scrollviewer的引用?我已经尝试了几乎所有我能想到的东西. ListBox位于WPF自定义控件中,因此我们使用Template.FindName获取对所有控件的引用.我的ListBox看起来像这样:
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)作为ScrollViewer的结果为空.
Template.FindName("Scroller",this) as ScrollViewer results in null.
有什么想法吗?
推荐答案
您可能试图过早地获得对ScrollViewer的引用.尝试在已加载的事件中移动代码,并检查代码是否仍返回null:
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:
在您的customControl/form构造函数中:
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);
}
这篇关于获取对C#中WPF ListBox的ScrollViewer的引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!