带有嵌套ScrollViewer的ScrollIntoView

时间:2011-07-29 11:16:56

标签: c# wpf datagrid scroll ui-virtualization

在我的应用程序中,我将一个Canvas包装在ScrollViewer中(Canvas比屏幕大小更大)。在这个画布上,我放置了其他控件。画布上的一个元素包含一个虚拟化的DataGrid(有2000多行......所以也需要滚动)。现在我有一个函数,它根据行元素的某些值(自动触发)在DataGrid中选择一行。选择行后,我调用

uxDataGrid.ScrollIntoView(uxDataGrid.SelectedItems[0]);

什么工作得很好。事实上,它正在努力实现。我想要的是,选择DataGrid中的元素,然后DataGrid应滚动到正确的位置。但是我的Canvas滚动浏览器也以某种方式接收了这个请求并且也在那里滚动。

我已经尝试拦截ScrollChangedEvent并设置处理标志。但它没有用。

Qustions:

1)如何限制ScrollIntoView调用对本地用户控件的影响。

2)如果不可能,我怎么能自己滚动?我需要计算scrollviewer的垂直偏移量,但由于它是虚拟化的,我不知道如何找出行高?

有什么建议吗?

我添加了一个快速示例来演示主要设置。当按下其中一个按钮时,我只想要滚动DataGrid,而不是滚动浏览器的ScrollViewer。

<Window x:Class="ScrollTest.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow" Height="350" Width="525">
<DockPanel>
    <StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal">
        <Button Click="Button1_Click">Scroll to 1</Button>
        <Button Click="Button100_Click">Scroll to 100</Button>
        <Button Click="Button200_Click">Scroll to 200</Button>
    </StackPanel>
    <ScrollViewer>
        <Canvas Width="5000" Height="5000">
            <DataGrid Name="uxDataGrid" ItemsSource="{Binding TestItems}" Width="500" Height="500"></DataGrid>
        </Canvas>
    </ScrollViewer>
</DockPanel>

public class TestItem
{
    public TestItem(int id)
    {
        Property1 = id.ToString();
        Property2 = "B";
    }
    public string Property1 { get; set; }
    public string Property2 { get; set; }
}
/// <summary>
/// Interaktionslogik für MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
    public IList<TestItem> TestItems { get; set; }
    public MainWindow()
    {
        TestItems = new List<TestItem>();
        for ( int i = 0; i < 300; i++ )
        {
            TestItems.Add(new TestItem(i));
        }

        InitializeComponent();
        DataContext = this;
    }


    private void Button1_Click( object sender, RoutedEventArgs e )
    {
        uxDataGrid.ScrollIntoView( TestItems[0]);
    }
    private void Button100_Click( object sender, RoutedEventArgs e )
    {
        uxDataGrid.ScrollIntoView( TestItems[99] );
    }
    private void Button200_Click( object sender, RoutedEventArgs e )
    {
        uxDataGrid.ScrollIntoView( TestItems[199] );
    }
}

1 个答案:

答案 0 :(得分:5)

好的......经过一些研究,我发现了正确的事件:它被称为RequestBringIntoViewEvent。当拦截那个时,它按预期工作:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        ...
        uxDataGrid.AddHandler( RequestBringIntoViewEvent, new RoutedEventHandler( HandleRequestBringIntoViewEvent ) );
    }

    private static void HandleRequestBringIntoViewEvent( object sender, RoutedEventArgs e )
    {
        e.Handled = true;
    }
    ...
}