我如何可以以编程方式滚动WPF列表视图?视图、方式、列表、WPF

2023-09-02 20:47:31 作者:脱缰的野马

是否有可能以编程方式滚动WPF列表视图?我知道的WinForms不这样做,对吗?

Is it possible to programmatically scroll a WPF listview? I know winforms doesn't do it, right?

我说的都说向上或向下滚动50个单位,等不得滚动整个项目的高度一次。

I am talking about say scrolling 50 units up or down, etc. Not scrolling an entire item height at once.

推荐答案

是的,你必须从ListView中抢ScrollViwer,或但一旦你有机会到这一点,你可以使用它,或者覆盖暴露的方法滚动。您也可以通过获取的主要内容区域,使用滚动它的实施IScrollInfo接口。

Yes, you'll have to grab the ScrollViwer from the ListView, or but once you have access to that, you can use the methods exposed by it or override the scrolling. You can also scroll by getting the main content area and using it's implementation of the IScrollInfo interface.

下面是一个小帮手得到的东西ScrollViwer组件像一个ListBox,ListView控件等。

Here's a little helper to get the ScrollViwer component of something like a ListBox, ListView, etc.

public static DependencyObject GetScrollViewer(DependencyObject o)
{
	// Return the DependencyObject if it is a ScrollViewer
	if (o is ScrollViewer)
	{ return o; }

	for (int i = 0; i < VisualTreeHelper.GetChildrenCount(o); i++)
	{
		var child = VisualTreeHelper.GetChild(o, i);

		var result = GetScrollViewer(child);
		if (result == null)
		{
			continue;
		}
		else
		{
			return result;
		}
	}
	return null;
}

然后你可以只使用.LineUp()和.LineDown()是这样的:

And then you can just use .LineUp() and .LineDown() like this:

private void OnScrollUp(object sender, RoutedEventArgs e)
{
	var scrollViwer = GetScrollViewer(uiListView) as ScrollViewer;

	if (scrollViwer != null)
	{
       // Logical Scrolling by Item
	   // scrollViwer.LineUp();
       // Physical Scrolling by Offset
       scrollViwer.ScrollToVerticalOffset(scrollViwer.VerticalOffset + 3);
	}
}

private void OnScrollDown(object sender, RoutedEventArgs e)
{
	var scrollViwer = GetScrollViewer(uiListView) as ScrollViewer;

	if (scrollViwer != null)
	{
        // Logical Scrolling by Item
	    // scrollViwer.LineDown();
        // Physical Scrolling by Offset
        scrollViwer.ScrollToVerticalOffset(scrollViwer.VerticalOffset + 3);
	}
}


<DockPanel>
    <Button DockPanel.Dock="Top"
			Content="Scroll Up"
			Click="OnScrollUp" />
	<Button DockPanel.Dock="Bottom"
			Content="Scroll Down"
			Click="OnScrollDown" />
	<ListView x:Name="uiListView">
		<!-- Content -->
	</ListView>
</DockPanel>

逻辑滚动通过阵容和LineDown暴露仍旧按项目滚动,如果你想通过你应该使用ScrollToHorizo​​ntal / VerticalOffset,我已经上面使用了一组量来滚动。如果你想要一些更复杂的太滚动,然后看看我在此给出了答案other问题。