Make scrollbar fade in / out

2019-09-16 19:23发布

问题:

I set my scroll bar to be hidden when you are not over the ScrollViewer and only shows when you hover over

This is the code I am using - it works great

<ControlTemplate.Triggers>
    <Trigger Property="IsMouseOver" Value="False">
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Hidden"/>
    </Trigger>

    <Trigger Property="IsMouseOver" Value="True">
        <Setter Property="ScrollViewer.VerticalScrollBarVisibility" Value="Visible"/>
    </Trigger>
</ControlTemplate.Triggers>

My question is, how can I make the scroll bar to fade in and out instead of just show/hide right away?

回答1:

Use a visual state (see http://msdn.microsoft.com/en-us/library/system.windows.visualstatemanager.aspx). This allows you to animate from the xaml directly

<VisualStateManager.VisualStateGroups>
    <VisualStateGroup x:Name="HideScrollbar">
        <VisualState x:Name="Invisible">                                    
            <Storyboard>
                <DoubleAnimation Storyboard.TargetName="scrollBar" Storyboard.TargetProperty="Opacity"                                              
                    To="0"
                    Duration="0:0:0.25"/>
                </Storyboard>
            </VisualState>
            <VisualState x:Name="Visible">
                <Storyboard>
                    <DoubleAnimation Storyboard.TargetName="scrollBar" Storyboard.TargetProperty="Opacity" 
                        To="1"
                        Duration="0:0:0.25"/>
                </Storyboard>
            </VisualState>
        </VisualStateGroup>
   </VisualStateManager.VisualStateGroups>

Couple this with a state change in your xaml.cs file

public void OnMouseOver(...)
{
    VisualStateManager.GoToState(this, "Visible", true);
}

public void OnMouseLeave(...)
{
    VisualStateManager.GoToState(this, "Invisible", true);
}