如何将ScrollViewer滚动到特定的RadioButton位置

时间:2018-05-20 14:58:15

标签: c# wpf vb.net

XAML

<Window x:Class="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">
<ScrollViewer x:Name="ScrollViewer1" CanContentScroll="True" SnapsToDevicePixels="True" VerticalScrollBarVisibility="Visible">
    <DockPanel LastChildFill="False">
        <RadioButton x:Name="RadioButton1" Content="RadioButton1" GroupName="MyGroup" Width="100" DockPanel.Dock="Top" Margin="30"/>
        <RadioButton x:Name="RadioButton2" Content="RadioButton2" GroupName="MyGroup" Width="100" DockPanel.Dock="Top" Margin="30"/>
        <RadioButton x:Name="RadioButton3" Content="RadioButton3" GroupName="MyGroup" Width="100" DockPanel.Dock="Top" Margin="30"/>
        <RadioButton x:Name="RadioButton4" Content="RadioButton4" GroupName="MyGroup" Width="100" DockPanel.Dock="Top" Margin="30"/>
        <RadioButton x:Name="RadioButton5" Content="RadioButton5" GroupName="MyGroup" Width="100" DockPanel.Dock="Top" Margin="30"/>
        <RadioButton x:Name="RadioButton6" Content="RadioButton6" GroupName="MyGroup" Width="100" DockPanel.Dock="Top" Margin="30"/>
        <RadioButton x:Name="RadioButton7" Content="RadioButton7" GroupName="MyGroup" Width="100" DockPanel.Dock="Top" Margin="30"/>
        <RadioButton x:Name="RadioButton8" Content="RadioButton8" GroupName="MyGroup" Width="100" DockPanel.Dock="Top" Margin="30"/>
    </DockPanel>
</ScrollViewer>
</Window>

vb.net

Class MainWindow 
Private Sub RadioButton5_Checked(sender As Object, e As RoutedEventArgs) Handles RadioButton5.Checked
    ScrollViewer1.ScrollToVerticalOffset(0)
End Sub
End Class

如果点击RadioButton5,您会看到ScrollViewer1滚动到零位置。所以,上面的代码很有用。

用户点击ScrollViewer1时,我希望RadioButton3滚动到RadioButton8位置。

Robert Levy 的答案看起来不错,但我不明白如何在这里实施 Robert Levy 的答案:How to scroll WPF ScrollViewer's content to specific location

1 个答案:

答案 0 :(得分:0)

如果要将按钮滚动到鼠标下方: 您可以使用

获取按钮相对于鼠标的位置
Point position = Mouse.GetPosition(RadioButton5);

然后使用

滚动到按钮
ScrollViewer1.ScrollToVerticalOffset(ScrollViewer1.VerticalOffset - position.Y);

如果我理解你,你可以将按钮滚动到列表顶部。你可以通过

达到目的
Point point = ScrollViewer1.TranslatePoint(new Point(), RadioButton5);
ScrollViewer1.ScrollToVerticalOffset(ScrollViewer1.VerticalOffset - point.Y);

我希望这是你试图做的。