首页 > 其他分享 >WPF TreeView 样式

WPF TreeView 样式

时间:2023-03-15 17:13:50浏览次数:52  
标签:样式 object value new WPF TreeView public

一、前言

TreeView控件在项目中使用比较频繁,普通的TreeView并不能满足我们的需求。因此我们需要滴对TreeView进行改造。下面的内容将介绍仿QQ联系人TreeView样式及TreeView数据绑定方法。

二、TreeView仿QQ联系人列表

准确的说不是仿QQ联系人列表,这个TreeView样式作为组织架构来使用更好。废话不多说,先看效果:

 2.1、基本思路

像这种联系人列表一般涉及到多层级数据,而且有很多数据是需要动态更新的,如果通过手动一条条增加数据反而更复杂,而且不方便。因此为了绑定数据方便我们使用分层模板HierarchicalDataTemplate。

分层模板中存在两种样式,一种是分组样式,一种是人员样式。不管是分组还是人员绑定的都是对象,这样我们在对象中添加一个属性来辨别是否为分组-IsGrouping。

默认的TreeView控件四周会有边距,因此需要设置下TreeView的样式。另外鼠标经过和鼠标选中的背景色需要变化,因此还需要设置TreeViewItem的样式。

根据思路,我们需要设置三个样式,TreeView样式,TreeViewItem样式,HierarchicalDataTemplate分层模板样式。另外为了自动计算下一级的边距,我们需要添加一个转换器IndentConverter。还需要一个转换器需要将布尔类型的IsGrouping转换为Visibility,还需要一个转换器来对Visibility取反。

这样三个样式,三个转换器。就可以实现我们上面的效果,另外还可以进行动态数据绑定。

2.2、样式代码

HierarchicalDataTemplate分层模板样式代码

复制代码
 <HierarchicalDataTemplate x:Key="ItemNode" ItemsSource="{Binding Children,Mode=TwoWay}">
            <Grid  Background="Transparent">
                <Grid.Resources>
                    <convert:BoolToVisible x:Key="boolToVisible"/>
                    <convert:VisibleToReverse x:Key="visibleToReverse"/>
                </Grid.Resources>
                <Grid MinHeight="30" x:Name="userinfo" Background="Transparent" Margin="-5 0 0 0" Visibility="{Binding Visibility,ElementName=groupinginfo,Converter={StaticResource visibleToReverse}}">
                    <Grid Height="50" x:Name="grid">
                        <Border Background="#62acf9" Width="40" Height="40" CornerRadius="4" HorizontalAlignment="Left" Margin="0 0 0 0">
                            <TextBlock Text="{Binding SurName}" FontSize="23" Foreground="White" VerticalAlignment="Center" HorizontalAlignment="Center"/>
                        </Border>
                        <TextBlock Text="{Binding Name}" Margin="50 7 0 0" FontSize="13"/>
                        <TextBlock Text="{Binding Info}" Foreground="#808080" Margin="50 30 0 0"/>
                        <TextBlock Text="{Binding Count,StringFormat={}{0}人}" Foreground="#808080" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="0 0 5 0"/>
                    </Grid>
                </Grid>
                <StackPanel MinHeight="25" x:Name="groupinginfo" Orientation="Horizontal" Background="Transparent" HorizontalAlignment="Left" Visibility="{Binding IsGrouping,Converter={StaticResource boolToVisible}}">

                    <TextBlock Text="{Binding DisplayName}" Margin="3 0" VerticalAlignment="Center" HorizontalAlignment="Left"/>
                </StackPanel>
            </Grid>
        </HierarchicalDataTemplate>
复制代码

TreeViewItem样式代码

复制代码
 <Style  x:Key="DefaultTreeViewItem" TargetType="{x:Type TreeViewItem}">
            <Setter Property="MinHeight" Value="25" />
            <Setter Property="Background" Value="Transparent" />
            <Setter Property="SnapsToDevicePixels" Value="True" />

            <Setter Property="Margin" Value="0" />
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type TreeViewItem}">
                        <ControlTemplate.Resources>
                            <convert:IndentConverter  x:Key="indentConverter"/>
                        </ControlTemplate.Resources>
                        <Grid Background="Transparent">
                            <Grid.RowDefinitions>
                                <RowDefinition/>
                                <RowDefinition/>
                            </Grid.RowDefinitions>
                            <Border Name="itemBackground" Background="{TemplateBinding Background}"  
                                BorderBrush="{TemplateBinding BorderBrush}"  
                                BorderThickness="{TemplateBinding BorderThickness}"  
                                Padding="{TemplateBinding Padding}">
                                <Grid Background="Transparent">
                                    <Grid x:Name="ItemRoot" Margin="{Binding Converter={StaticResource indentConverter},RelativeSource={RelativeSource TemplatedParent}}" Background="Transparent">
                                        <Grid.ColumnDefinitions>
                                            <ColumnDefinition Width="16" />
                                            <ColumnDefinition Width="*"/>
                                        </Grid.ColumnDefinitions>

                                        <ToggleButton x:Name="Expander" HorizontalAlignment="Left" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}">
                                            <ToggleButton.Style>
                                                <Style TargetType="{x:Type ToggleButton}">
                                                    <Setter Property="Focusable" Value="False"/>
                                                    <Setter Property="Width" Value="16"/>
                                                    <Setter Property="Height" Value="16"/>
                                                    <Setter Property="Template">
                                                        <Setter.Value>
                                                            <ControlTemplate TargetType="{x:Type ToggleButton}">
                                                                <Border Background="Transparent" Height="16" Padding="5" Width="16">
                                                                    <Path x:Name="ExpandPath" Data="M0,0 L0,6 L6,0 z" Fill="#66645e" Stroke="#66645e">
                                                                        <Path.RenderTransform>
                                                                            <RotateTransform Angle="135" CenterY="3" CenterX="3"/>
                                                                        </Path.RenderTransform>
                                                                    </Path>
                                                                </Border>
                                                                <ControlTemplate.Triggers>
                                                                    <Trigger Property="IsChecked" Value="True">
                                                                        <Setter Property="RenderTransform" TargetName="ExpandPath">
                                                                            <Setter.Value>
                                                                                <RotateTransform Angle="180" CenterY="3" CenterX="3"/>
                                                                            </Setter.Value>
                                                                        </Setter>
                                                                        <Setter Property="Fill" TargetName="ExpandPath" Value="#66645e"/>
                                                                        <Setter Property="Stroke" TargetName="ExpandPath" Value="#66645e"/>
                                                                    </Trigger>
                                                                    <Trigger Property="IsMouseOver" Value="True">
                                                                        <Setter Property="Stroke" TargetName="ExpandPath" Value="#66645e"/>
                                                                        <Setter Property="Fill" TargetName="ExpandPath" Value="#66645e"/>
                                                                    </Trigger>
                                                                    <MultiTrigger>
                                                                        <MultiTrigger.Conditions>
                                                                            <Condition Property="IsMouseOver" Value="True"/>
                                                                            <Condition Property="IsChecked" Value="True"/>
                                                                        </MultiTrigger.Conditions>
                                                                        <Setter Property="Stroke" TargetName="ExpandPath" Value="#66645e"/>
                                                                        <Setter Property="Fill" TargetName="ExpandPath" Value="#66645e"/>
                                                                    </MultiTrigger>
                                                                </ControlTemplate.Triggers>
                                                            </ControlTemplate>
                                                        </Setter.Value>
                                                    </Setter>
                                                </Style>
                                            </ToggleButton.Style>
                                        </ToggleButton>
                                        <ContentPresenter Grid.Column="1" x:Name="PART_Header" ContentSource="Header"  
                                                 HorizontalAlignment="Stretch" >

                                        </ContentPresenter>
                                    </Grid>
                                </Grid>

                            </Border>
                            <ItemsPresenter x:Name="ItemsHost" Grid.Row="1"/>
                        </Grid>

                        <ControlTemplate.Triggers>
                            <DataTrigger Binding="{Binding IsGrouping}" Value="false">
                                <Setter Property="Visibility" TargetName="Expander" Value="Hidden"/>
                            </DataTrigger>
                            <Trigger Property="HasItems" Value="False">
                                <Setter Property="Visibility" TargetName="Expander" Value="Collapsed"/>
                            </Trigger>
                            <Trigger Property="IsExpanded" Value="False">
                                <Setter Property="Visibility" TargetName="ItemsHost" Value="Collapsed"/>
                            </Trigger>

                            <Trigger Property="IsSelected" Value="True">
                                <Setter Property="Background" TargetName="itemBackground" Value="#FAE388"/>
                            </Trigger>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsFocused" Value="False"/>
                                    <Condition SourceName="itemBackground" Property="IsMouseOver" Value="true"/>
                                </MultiTrigger.Conditions>
                                <Setter Property="Background" Value=" #fceeb9" TargetName="itemBackground"/>
                            </MultiTrigger>
                            <Trigger Property="IsEnabled" Value="False">
                                <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                            </Trigger>
                        </ControlTemplate.Triggers>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
复制代码

TreeView样式代码

复制代码
  <Style x:Key="DefaultTreeView" TargetType="{x:Type TreeView}">
            <Setter Property="ScrollViewer.CanContentScroll" Value="True" />
            <Setter Property="VirtualizingStackPanel.IsVirtualizing" Value="True"></Setter>
            <Setter Property="VirtualizingStackPanel.VirtualizationMode" Value="Recycling" />
            <Setter Property="ScrollViewer.IsDeferredScrollingEnabled" Value="False" />
            <Setter Property="ItemContainerStyle" Value="{StaticResource DefaultTreeViewItem}"></Setter>
            <Setter Property="Padding" Value="0"/>
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel IsItemsHost="True" Margin="0"/>
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Style>
复制代码

2.3、转换器代码

复制代码
 public class IndentConverter : IValueConverter
    {

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            double colunwidth = 10;
            double left = 0.0;


            UIElement element = value as TreeViewItem;
            while (element.GetType() != typeof(TreeView))
            {
                element = (UIElement)VisualTreeHelper.GetParent(element);
                if (element.GetType() == typeof(TreeViewItem))
                    left += colunwidth;
            }
            return new Thickness(left, 0, 0, 0);
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }

    }

    public class BoolToVisible : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((bool)value)
                return Visibility.Visible;
            else
                return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }

    public class VisibleToReverse : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if ((Visibility)value == Visibility.Visible)
                return Visibility.Collapsed;
            else
                return Visibility.Visible;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
复制代码

2.4、引用示例

  <TreeView x:Name="TreeViewOrg" BorderThickness="1" BorderBrush="#BBB" Background="Transparent" Width="280" Height="500" Margin="10" ItemTemplate="{StaticResource ItemNode}" Style="{StaticResource DefaultTreeView}">
            </TreeView>

2.5、初始化数据源及绑定对象

复制代码
public MainWindow()
        {
            InitializeComponent();
            OrgList = new ObservableCollection<OrgModel>()
            {
                new OrgModel()
                {
                    IsGrouping=true,
                    DisplayName="单位名称(3/7)",
                    Children=new ObservableCollection<OrgModel>()
                    {
                        new OrgModel(){
                            IsGrouping=true,
                            DisplayName="未分组联系人(2/4)",
                            Children=new ObservableCollection<OrgModel>()
                            {
                                new OrgModel(){
                                    IsGrouping=false,
                                    SurName="刘",
                                    Name="刘棒",
                                    Info="我要走向天空!",
                                    Count=3
                                }
                            }
                        }
                    },
                }

            };
            TreeViewOrg.ItemsSource = OrgList;
        }

        public ObservableCollection<OrgModel> OrgList { get; set; }

        public class OrgModel
        {
            public bool IsGrouping { get; set; }
            public ObservableCollection<OrgModel> Children { get; set; }
            public string DisplayName { get; set; }
            public string SurName { get; set; }
            public string Name { get; set; }
            public string Info { get; set; }
            public int Count { get; set; }
        }
复制代码

 

所有代码已经上传到github:https://github.com/cmfGit/WpfDemo.git

标签:样式,object,value,new,WPF,TreeView,public
From: https://www.cnblogs.com/lzjsky/p/17219184.html

相关文章

  • VUE基础:组件CSS样式、props属性
    VUE基础部分组件css样式例子<stylelang="less">//这里记得改名,然后给div也加名字.comName-container{padding:1020px20px;background-color:lightskyblue......
  • New!界面控件DevExpress WPF 2023产品路线图曝光
    DevExpressWPF拥有120+个控件和库,将帮助您交付满足甚至超出企业需求的高性能业务应用程序。通过DevExpressWPF能创建有着强大互动功能的XAML基础应用程序,这些应用程序专......
  • WPF Binding属性
    Binding可以让前台和后台的属性绑定在一起。实现实时更新。比如前台xaml<StackPanel><TextBoxx:Name="txtBox"BorderBrush="Black"Margin="5"/>......
  • 覆盖element-ui原生样式
    使用深度选择器/deep/进行作用域穿透,不需要去掉style 标签 scoped 属性。只需要在父类class下的element-ui组件class前加上/deep/,就可以修改默认样式如下所示改变原......
  • element-table 相关样式修改
    1.表格整体背景色修改/*表格整体背景色*/::v-deep.el-table,::v-deep.el-table__expanded-cell{background-color:transparent!important;}2.表格内tr......
  • WPF 自定义ComboBox样式,自定义多选控件
    一、ComboBox基本样式ComboBox有两种状态,可编辑和不可编辑状态。通过设置IsEditable属性可以切换控件状态。先看基本样式效果:基本样式代码如下:<!--ComboBox-->......
  • 相对定位与绝对定位如何让页面样式居中的?
        position 定位允许您从正常的文档流布局中取出元素,并使它们具有不同的行为,例如放在另一个元素的上面,或者始终保持在浏览器视窗内的同一位置。CSS中定位分类有四......
  • (原创)【B4A】一步一步入门07:EditText,文本框、密码框、键盘样式、提示文本(控件篇03)
    一、前言本篇教程,我们来讲一下常用的控件:EditText(文本输入框)。本篇教程将会讲解文本框的基本使用,如:提示文本、密码文本、键盘样式等。相信看完的你,一定会有所收获!本文......
  • EasyCVR视频融合平台国标级联编辑页面的样式优化
    EasyCVR视频融合平台部署轻快、功能灵活,可支持多协议、多类型设备接入,在视频能力上,可实现视频直播、录像、回放、检索、云存储、告警上报、语音对讲、集群、智能分析以及平......
  • WPF ItemsControl/ListBox/ListView 控件样式
    一、前言ItemsControl、ListBox、ListView这三种控件在WPF中都可作为列表信息展示控件。我们可以通过修改这三个控件的样式来展示我们的列表信息。既然都是展示列表信息......