获取ListView的垂直滚动条位置

时间:2017-10-27 20:10:22

标签: c# wpf wpf-controls

我有一个WPF应用程序,需要在每次用户滚动时从顶部获取垂直滚动条更改。这是我的XAML:

<ListView ItemsSource="{Binding Images, UpdateSourceTrigger=PropertyChanged}" 
    ScrollViewer.HorizontalScrollBarVisibility="Disabled" Name="ImageListView"
    ItemTemplate="{StaticResource ImageTemplate}"  
    ScrollViewer.ScrollChanged="listBox_ScrollChanged">
    <ListView.ItemsPanel>
        <ItemsPanelTemplate>
            <wpfControls:VirtualizingWrapPanel IsItemsHost="True" 
                Visibility="{Binding ShowImages, 
                Converter={StaticResource BooleanToVisibilityConverter}, 
                FallbackValue=Collapsed}" />
        </ItemsPanelTemplate>
    </ListView.ItemsPanel>
</ListView>

<DataTemplate x:Key="ImageTemplate">
    <materialDesign:Card Height="Auto" Width="Auto">
        <StackPanel Orientation="Vertical" Margin="5">
            <Image Width="165" Stretch="Fill" Source="{Binding Url}" 
                ToolTipService.ShowDuration="9000000">
                <Image.ToolTip>
                    <ToolTip DataContext="{Binding PlacementTarget, 
                        RelativeSource={RelativeSource Self}}" HasDropShadow="True">
                        <Border BorderBrush="Black" BorderThickness="0" 
                           Margin="5,7,5,5">
                            <Image Source="{Binding Source}" Width="595" 
                                Stretch="Uniform" />
                        </Border>
                    </ToolTip>
                </Image.ToolTip>
            </Image>
            <TextBox FontWeight="Bold" Text="{Binding Filename, Mode=OneWay}" 
                IsReadOnly="True" />
        </StackPanel>
    </materialDesign:Card>
</DataTemplate>

请注意wpfControls使用此:xmlns:wpfControls="clr-namespace:Digimezzo.WPFControls;assembly=Digimezzo.WPFControls"

这是代码隐藏的代码:

public MainWindow()
{
    InitializeComponent();
    listViewScrollViewer = FindScrollViewer(ImageListView);
    scrollVerticalPosition = 0;
}

private ScrollViewer listViewScrollViewer;
private double scrollVerticalPosition;

private void listBox_ScrollChanged(object sender, ScrollChangedEventArgs e)
{
    scrollVerticalPosition = e.VerticalChange;
}

// From https://stackoverflow.com/a/21443193/177416
private ScrollViewer FindScrollViewer(DependencyObject d)
{
    if (d is ScrollViewer)
        return d as ScrollViewer;

    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(d); i++)
    {
        var sw = FindScrollViewer(VisualTreeHelper.GetChild(d, i));
        if (sw != null) return sw;
    }
    return null;
}

我需要从e中读取listBox_ScrollChanged()以从顶部进行垂直更改?然后我会使用ScrollToVerticalOffset()稍后将用户返回到该位置。

0 个答案:

没有答案