保持滚动查看器中某个控件的位置

本文关键字:控件 位置 滚动 | 更新日期: 2023-09-27 18:37:19

假设我有这样的 XAML 代码:

<UserControl x:Class="Sample.MyClass"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="220" d:DesignWidth="750">
    <ScrollViewer Width="730" Height="150" CanContentScroll="True" HorizontalScrollBarVisibility="Visible">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition />
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="50" />
                <ColumnDefinition Width="680" />
            </Grid.ColumnDefinitions>
            <TextBox Width="50" Height="200" Grid.Row="0" Grid.Column="0" />
            <TextBox Width="680" Height="200" Grid.Row="0" Grid.Column="1" />
        </Grid>
    </ScrollViewer>
</UserControl>

现在,当我向右滚动时,我希望第一个TextBox完全可见。换句话说 - 我希望水平滚动(仅水平滚动)仅适用于第二个TextBox,垂直滚动适用于两者。我不能把第一个放在ScrollViewer之外,因为这样垂直滚动就不起作用了。

举一个更现实的例子:在VisualStudio中,您有一个文本区域,您可以在其中输入代码。在左侧有一个面板,显示行号和代码折叠。如果垂直滚动文本区域,左侧面板也会向下或向上滚动。水平滚动文本区域时,只有文本区域受其影响。

保持滚动查看器中某个控件的位置

您可以尝试修改 XAML,如下所示:

<UserControl x:Class="Sample.MyClass"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="220" d:DesignWidth="750">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="50" />
            <ColumnDefinition Width="680" />
        </Grid.ColumnDefinitions>
        <ScrollViewer Grid.Row="0" Grid.Column="0" 
                  CanContentScroll="True" 
                  VerticalScrollBarVisibility="Visible" 
                  HorizontalAlignment="Stretch">
            <TextBox  />
       </ScrollViewer>
       <ScrollViewer Grid.Row="0" Grid.Column="1"  
                  CanContentScroll="True" 
                  VerticalScrollBarVisibility="Visible" 
                  HorizontalScrollBarVisibility="Visible" 
                  HorizontalAlignment="Stretch" 
                  VerticalAlignment="Stretch">
            <TextBox />
        </ScrollViewer>
    </Grid>
</UserControl>

希望这可能会有所帮助。

我想你想做的是 svnc 2 滚动查看器,

你可以用巫毒教背后的一些代码来做到这一点,看看这个

每当任何一个在 wpf 中滚动时,两个滚动查看器的同步滚动