wpf中TreeView的滚动条

先看效果

TreeView中是自带有滚动条的,左右滚动和上下滚动,TreeView的内部是很复杂的。

使用snoop软件可以看到,有一个上下滚动,和一个左右滚动

上下滚动

 左右滚动

1.建立一个wpf项目,文件总览 

2.xaml文件代码

<Window x:Class="TreeView.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:TreeView"
        mc:Ignorable="d"
        Title="MainWindow" Height="450" Width="800">
    <Window.Resources>
        <Style TargetType="ScrollBar" BasedOn="{StaticResource for_scrollbar}"/>
        <Style TargetType="ScrollViewer" BasedOn="{StaticResource for_scrollviewer}"/>
    </Window.Resources>
    <Grid>
        <StackPanel Margin="10" Background="#00D61212">
            <StackPanel.ContextMenu>
                <ContextMenu>
                    <MenuItem x:Name="cmmiModuleRefresh" Header="刷新" />
                    <MenuItem x:Name="cmmiModuleExpandAll" Header="展开"/>
                    <MenuItem x:Name="cmmiModuleCollapseAll" Header="折叠" />
                </ContextMenu>
            </StackPanel.ContextMenu>
            <TreeView Name="trvPersons" Width="150" Height="200"  Foreground="#FF05C7CB" BorderBrush="#00ACACAC" Background="#004682B4" >
                <TreeView.ItemTemplate>
                    <HierarchicalDataTemplate ItemsSource="{Binding Children}">
                        <StackPanel Orientation="Horizontal">
                            <Image Source="/TreeView;component/Images/1.png" Margin="0,0,5,0" />
                            <TextBlock Text="{Binding Name}" Margin="0,0,4,0" Foreground='#FF05C7CB' />
                        </StackPanel>
                    </HierarchicalDataTemplate>
                </TreeView.ItemTemplate>
                <TreeView.ItemContainerStyle>
                    <Style TargetType="TreeViewItem">
                        <Setter Property="IsSelected" Value="{Binding IsSelected}" />
                        <Setter Property="IsExpanded" Value="{Binding IsExpanded}" />
                    </Style>
                </TreeView.ItemContainerStyle>
            </TreeView>
        </StackPanel>
        <StackPanel Background="Red" Width="200" Height="200" HorizontalAlignment="Left">
            <ScrollBar x:Name="verticalScrollBarForModuleTree" ViewportSize="1" FontSize="40" MinWidth="30" MinHeight="50"   Margin="0" Background="#FF10516D" Width="20" HorizontalAlignment="Right" Height="200" Foreground="#00E81212" BorderBrush="#00E01414" OpacityMask="#FFFF1818" SmallChange="10"  >
                <ScrollBar.ContextMenu>
                    <ContextMenu Visibility="Hidden" />
                </ScrollBar.ContextMenu>
               
            </ScrollBar>

        </StackPanel>
    </Grid>
</Window>

3.后台cs文件代码

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace TreeView
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            List<Person> persons = new List<Person>();
            Person person1 = new Person() { Name = "John DoeJohn DoeJohn Doe", Age = 42 };
            Person person2 = new Person() { Name = "Jane DoeJohn DoeJohn Doe", Age = 39 };
            Person child1 = new Person() { Name = "Sammy DoeJohn DoeJohn Doe", Age = 13 };
            person1.Children.Add(child1);
            person2.Children.Add(child1);
            person2.Children.Add(new Person() { Name = "Jenny MoeJohn Doe", Age = 17 });
            Person person3 = new Person() { Name = "Becky ToJohn DoeJohn Doe", Age = 25 };
            persons.Add(person1);
            persons.Add(person2);
            persons.Add(person3);
            persons.Add(person1);
            persons.Add(person2);
            persons.Add(person3);
            persons.Add(person1);
            persons.Add(person2);
            persons.Add(person3);
            persons.Add(person1);
            persons.Add(person2);
            persons.Add(person3);
            persons.Add(person1);
            persons.Add(person2);
            persons.Add(person3);
            //person2.IsExpanded = true;
            //person2.IsSelected = true;
            trvPersons.ItemsSource = persons;
        }

        private void cmmiModuleRefresh_Click(object sender, RoutedEventArgs e)
        {
            //刷新,重新绑定数据 	trvPersons.ItemsSource= null;
        }

        private void cmmiModuleExpandAll_Click(object sender, RoutedEventArgs e)
        {
            SetNodeExpandedState(trvPersons, true);

        }

        private void cmmiModuleCollapseAll_Click(object sender, RoutedEventArgs e)
        {
            SetNodeExpandedState(trvPersons, false);
        }

        private void SetNodeExpandedState(ItemsControl control, bool expandNode)
        {
            try
            {
                if (control != null)
                {
                    foreach (object item in control.Items)
                    {
                        TreeViewItem treeItem = control.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;

                        if (treeItem != null && treeItem.HasItems)
                        {
                            treeItem.IsExpanded = expandNode;

                            if (treeItem.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
                            {
                                treeItem.UpdateLayout();
                            }

                            SetNodeExpandedState(treeItem as ItemsControl, expandNode);
                        }
                    }
                }
            }
            catch (Exception ex)
            {

            }
        }
    }

    public class Person : TreeViewItemBase
    {
        public Person()
        {
            this.Children = new ObservableCollection<Person>();
        }
        public string Name { get; set; }
        public int Age { get; set; }
        public ObservableCollection<Person> Children { get; set; }
    }


    public class TreeViewItemBase : INotifyPropertyChanged
    {
        private bool isSelected;
        public bool IsSelected
        {
            get { return this.isSelected; }
            set
            {
                if (value != this.isSelected)
                {
                    this.isSelected = value;
                    NotifyPropertyChanged("IsSelected");
                }
            }
        }
        private bool isExpanded;
        public bool IsExpanded
        {
            get { return this.isExpanded; }
            set
            {
                if (value != this.isExpanded)
                {
                    this.isExpanded = value;
                    NotifyPropertyChanged("IsExpanded");
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string propName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
    }
}

4.ScrollViewer.xaml样式文件

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <!-- ScrollViewer 滚动条 -->
    <Style x:Key="ScrollBarThumb" TargetType="{x:Type Thumb}">
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="IsTabStop" Value="false"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Thumb}">
                    <Grid>
                        <!--滚动条颜色-->
                        <Border Background="#646465" CornerRadius="3"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <!--滚动条横条底色-->
    <Style x:Key="HorizontalScrollBarPageButton" TargetType="{x:Type RepeatButton}">
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Focusable" Value="false"/>
        <Setter Property="IsTabStop" Value="false"/>
        <Setter Property="Opacity" Value="0.2"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RepeatButton}">
                    <Rectangle Fill="{TemplateBinding Background}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <!--滚动条竖条底色-->
    <Style x:Key="VerticalScrollBarPageButton" TargetType="{x:Type RepeatButton}">
        <Setter Property="OverridesDefaultStyle" Value="true"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Focusable" Value="false"/>
        <Setter Property="IsTabStop" Value="false"/>
        <Setter Property="Opacity" Value="0.2"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RepeatButton}">
                    <Rectangle Fill="{TemplateBinding Background}" Width="{TemplateBinding Width}" Height="{TemplateBinding Height}"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!--滚动条上下按钮-->
    <Style x:Key="VerticalScrollBarPageButton2" TargetType="{x:Type RepeatButton}">
        <Setter Property="OverridesDefaultStyle"  Value="true"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Focusable" Value="false"/>
        <Setter Property="IsTabStop" Value="false"/>
        <Setter Property="Opacity"  Value="0"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type RepeatButton}">
                    <Rectangle Fill="#90000000" Width="0" Height="0"/>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
    <Style x:Key="for_scrollbar" TargetType="{x:Type ScrollBar}">
        <Setter Property="Stylus.IsPressAndHoldEnabled" Value="false"/>
        <Setter Property="Stylus.IsFlicksEnabled" Value="false"/>
        <Setter Property="Background" Value="Transparent"/>
        <Setter Property="Margin" Value="0,1,1,6"/>
        <Setter Property="Width"  Value="10"/>
        <Setter Property="MinWidth"  Value="5"/>
        <Setter Property="Opacity"   Value="0.2"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ScrollBar}">
                    <Grid x:Name="Bg" SnapsToDevicePixels="true">
                        <Grid.RowDefinitions>
                            <RowDefinition Height="auto"></RowDefinition>
                            <RowDefinition Height="*"></RowDefinition>
                            <RowDefinition Height="auto"></RowDefinition>
                        </Grid.RowDefinitions>
                        <RepeatButton  Grid.Row="0" Style="{StaticResource VerticalScrollBarPageButton2}" Command="{x:Static ScrollBar.PageUpCommand}"/>
                        <Track x:Name="PART_Track"   Grid.Row="1" IsEnabled="{TemplateBinding IsMouseOver}" IsDirectionReversed="true">
                            <Track.DecreaseRepeatButton>
                                <RepeatButton Style="{StaticResource VerticalScrollBarPageButton}" Command="{x:Static ScrollBar.PageUpCommand}"/>
                            </Track.DecreaseRepeatButton>
                            <Track.IncreaseRepeatButton>
                                <RepeatButton Style="{StaticResource VerticalScrollBarPageButton}" Command="{x:Static ScrollBar.PageDownCommand}"/>
                            </Track.IncreaseRepeatButton>
                            <Track.Thumb>
                                <Thumb Style="{StaticResource ScrollBarThumb}"/>
                            </Track.Thumb>
                        </Track>
                        <RepeatButton Grid.Row="2" Style="{StaticResource VerticalScrollBarPageButton2}" Command="{x:Static ScrollBar.PageDownCommand}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
        <Style.Triggers>
            <Trigger Property="Orientation" Value="Horizontal">
                <Setter Property="Background"  Value="Transparent"/>
                <Setter Property="Margin" Value="1,0,6,1"/>
                <Setter Property="Height"   Value="5"/>
                <Setter Property="MinHeight"  Value="5"/>
                <Setter Property="Width"    Value="Auto"/>
                <Setter Property="Opacity" Value="0.2"/>
                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="{x:Type ScrollBar}">
                            <Grid x:Name="Bg" SnapsToDevicePixels="true">
                                <Track x:Name="PART_Track" IsEnabled="{TemplateBinding IsMouseOver}">
                                    <Track.DecreaseRepeatButton>
                                        <RepeatButton Style="{StaticResource HorizontalScrollBarPageButton}"  Command="{x:Static ScrollBar.PageLeftCommand}"/>
                                    </Track.DecreaseRepeatButton>
                                    <Track.IncreaseRepeatButton>
                                        <RepeatButton Style="{StaticResource HorizontalScrollBarPageButton}"  Command="{x:Static ScrollBar.PageRightCommand}"/>
                                    </Track.IncreaseRepeatButton>
                                    <Track.Thumb>
                                        <Thumb Style="{StaticResource ScrollBarThumb}"/>
                                    </Track.Thumb>
                                </Track>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>
            </Trigger>
        </Style.Triggers>
    </Style>
    <!--鼠标的动画效果,进入和退出-->
    <Style x:Key="for_scrollviewer"
           TargetType="{x:Type ScrollViewer}">
        <Setter Property="BorderBrush" Value="LightGray"/>
        <Setter Property="BorderThickness" Value="0"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type ScrollViewer}">
                    <Border BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" SnapsToDevicePixels="True">
                        <Grid Background="{TemplateBinding Background}">
                            <ScrollContentPresenter  Cursor="{TemplateBinding Cursor}" Margin="{TemplateBinding Padding}" ContentTemplate="{TemplateBinding ContentTemplate}"/>
                            <ScrollBar x:Name="PART_VerticalScrollBar"
                                       HorizontalAlignment="Right"
                                       Maximum="{TemplateBinding ScrollableHeight}"
                                       Orientation="Vertical"
                                       Style="{StaticResource for_scrollbar}"
                                       ViewportSize="{TemplateBinding ViewportHeight}"
                                       Value="{TemplateBinding VerticalOffset}"
                                       Visibility="{TemplateBinding ComputedVerticalScrollBarVisibility}"/>
                            <ScrollBar x:Name="PART_HorizontalScrollBar"
                                       Maximum="{TemplateBinding ScrollableWidth}"
                                       Orientation="Horizontal"
                                       Style="{StaticResource for_scrollbar}"
                                       VerticalAlignment="Bottom"
                                       Value="{TemplateBinding HorizontalOffset}"
                                       ViewportSize="{TemplateBinding ViewportWidth}"
                                       Visibility="{TemplateBinding ComputedHorizontalScrollBarVisibility}"/>
                        </Grid>
                    </Border>
                    <ControlTemplate.Triggers>
                        <EventTrigger RoutedEvent="ScrollChanged" >
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation
                                        Storyboard.TargetName="PART_VerticalScrollBar"
                                        Storyboard.TargetProperty="Opacity"
                                        To="0.8"
                                        Duration="0:0:1"/>
                                    <DoubleAnimation
                                        Storyboard.TargetName="PART_VerticalScrollBar"
                                        Storyboard.TargetProperty="Opacity"
                                        To="0.2"
                                        Duration="0:0:1"
                                        BeginTime="0:0:1"/>
                                    <DoubleAnimation
                                        Storyboard.TargetName="PART_HorizontalScrollBar"
                                        Storyboard.TargetProperty="Opacity"
                                        To="0.8"
                                        Duration="0:0:1"/>
                                    <DoubleAnimation
                                        Storyboard.TargetName="PART_HorizontalScrollBar"
                                        Storyboard.TargetProperty="Opacity"
                                        To="0.2"
                                        Duration="0:0:1"
                                        BeginTime="0:0:1"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="MouseEnter"
                                      SourceName="PART_VerticalScrollBar">
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation
                                        Storyboard.TargetName="PART_VerticalScrollBar"
                                        Storyboard.TargetProperty="Opacity"
                                        To="0.8"
                                        Duration="0:0:0.7"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="MouseLeave"
                                      SourceName="PART_VerticalScrollBar">
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation
                                        Storyboard.TargetName="PART_VerticalScrollBar"
                                        Storyboard.TargetProperty="Opacity"
                                        To="0.2"
                                        Duration="0:0:0.7"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="MouseEnter"
                                      SourceName="PART_HorizontalScrollBar">
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation
                                        Storyboard.TargetName="PART_HorizontalScrollBar"
                                        Storyboard.TargetProperty="Opacity"
                                        To="0.8"
                                        Duration="0:0:0.7"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                        <EventTrigger RoutedEvent="MouseLeave"
                                      SourceName="PART_HorizontalScrollBar">
                            <BeginStoryboard>
                                <Storyboard>
                                    <DoubleAnimation
                                        Storyboard.TargetName="PART_HorizontalScrollBar"
                                        Storyboard.TargetProperty="Opacity"
                                        To="0.2"
                                        Duration="0:0:0.7"/>
                                </Storyboard>
                            </BeginStoryboard>
                        </EventTrigger>
                    </ControlTemplate.Triggers>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

    <!--默认ScrollBar,打开后,全局调用-->
    <!--<Style TargetType="ScrollBar" BasedOn="{StaticResource for_scrollbar}"/>-->

    <!--默认ScrollView,鼠标触发效果-->
    <!--<Style TargetType="ScrollViewer" BasedOn="{StaticResource for_scrollviewer}"/>-->
</ResourceDictionary>

5.配置App.xaml

<Application x:Class="TreeView.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:local="clr-namespace:TreeView"
             StartupUri="MainWindow.xaml">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="pack://application:,,,/TreeView;component/ScrollViewer.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

 6.效果

拓展

展开和收缩功能,直接传递TreeView控件和true或者false

	private void SetNodeExpandedState(ItemsControl control, bool expandNode)
		{
			try
			{
				if (control != null)
				{
					foreach (object item in control.Items)
					{
						TreeViewItem treeItem = control.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;

						if (treeItem != null && treeItem.HasItems)
						{
							treeItem.IsExpanded = expandNode;

							if (treeItem.ItemContainerGenerator.Status != System.Windows.Controls.Primitives.GeneratorStatus.ContainersGenerated)
							{
								treeItem.UpdateLayout();
							}

							SetNodeExpandedState(treeItem as ItemsControl, expandNode);
						}
					}
				}
			}
			catch (Exception ex)
			{
				
			}
		}

上面操作是某一个界面使用的

如果需要全局引用,去掉界面上面的代码

<!--<Style TargetType="ScrollBar" BasedOn="{StaticResource for_scrollbar}"/>
        <Style TargetType="ScrollViewer" BasedOn="{StaticResource for_scrollviewer}"/>-->

打开ScrollViewer.xaml的代码即可

    <!--默认ScrollBar,打开后,全局调用-->
    <Style TargetType="ScrollBar" BasedOn="{StaticResource for_scrollbar}"/>

    <!--默认ScrollView,鼠标触发效果-->
    <Style TargetType="ScrollViewer" BasedOn="{StaticResource for_scrollviewer}"/>

ScrollBar控件中的ViewportSize="1"属性,可以设置滑块的大小

TreeView中的滑块大小是变化的,似乎设置不了固定的大小,数据越少,滑块大小就越小

for_scrollviewer风格是鼠标进入的动画,可以对其进行修改,等等,其中有很多功能,可以根据对应的样式进行修改。

  • 0
    点赞
  • 0
    收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
©️2022 CSDN 皮肤主题:精致技术 设计师:CSDN官方博客 返回首页
评论 1

打赏作者

故里2130

你的鼓励将是我创作的最大动力

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值