始终在ScrollViewer滚动条中显示拇指

时间:2018-08-02 14:19:00

标签: c# wpf scrollviewer

如果ScrollViewer的内容小于可用区域,如何使ScrollViewer控件的滚动条始终显示滚动条的大拇指,并且大拇指最大长度?

采用以下XAML:

<Window x:Class="WpfApplication8.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication8"
        mc:Ignorable="d"
        Title="MainWindow" Height="200" Width="200">
    <ScrollViewer HorizontalScrollBarVisibility="Visible" 
                  VerticalScrollBarVisibility="Visible">
        <Grid Height="300" Width="300" Background="Red">

        </Grid>
    </ScrollViewer>
</Window>

将窗口调整为小于300x300像素网格的大小将使水平和垂直滚动条中的拇指均出现。

但是,当将窗口大小增加到大于300x300像素网格时,水平和垂直滚动条都消失了。

1 个答案:

答案 0 :(得分:0)

  

始终显示滚动条拇指

一种可能性是订阅Track事件(即您单击并隐藏的部分)IsVisibilityChanged事件并强行显示:

HackTheTrack(scrollViewer.FindChildren<Track>().First());
HackTheTrack(scrollViewer.FindChildren<Track>().Skip(1).Single()); // second track

void HackTheTrack(Track track)
{
    track.Visibility = Visibility.Visible;
    track.IsVisibleChanged += (s, ee) =>
    {
        if (track.Visibility != Visibility.Visible)
            track.Visibility = Visibility.Visible;
    };
}

您将需要以下扩展方法:

public static IEnumerable<T> FindChildren<T>(this DependencyObject @this) where T : DependencyObject
{
    if (@this == null)
        yield break;
    for (int i = 0; i < VisualTreeHelper.GetChildrenCount(@this); i++)
    {
        var child = VisualTreeHelper.GetChild(@this, i);
        var result = child as T;
        if (result != null)
            yield return result;
        foreach (var value in FindChildren<T>(child))
            yield return value;
    }
    yield break;
}

但这看起来很混乱: