Use case of TreeView control in WPF

Keywords: C# Windows

WPF is more convenient in general. The main changes are Listview and treeview controls. Treeview seems to be a highly criticized control in WPF, which many people say is not easy to use. My demo is mainly to use the treeview control in WPF to realize the picture viewing function, such as simple Grid layout, treeview control to add icons, some events of treeview control, display statistics, and read file operation.

Design sketch:

Front end main code:

<Window x:Class="TreeViewDemo.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:TreeViewDemo"
        mc:Ignorable="d"
        Title="WPF in TreeViewDemo" Height="964.8" Width="1718.2" Background="#FFEEEEEE" Loaded="Window_Loaded">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="166*"/>
            <ColumnDefinition Width="1545*"/>
        </Grid.ColumnDefinitions>
        <TabControl  
            SelectedIndex="{Binding Model.TabIndex,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
            HorizontalAlignment="Stretch" 
            SelectionChanged="TabControl_SelectionChanged"
            VerticalAlignment="Stretch" Background="White" Margin="5,0,10.333,0.333" Grid.ColumnSpan="2">
    
            <TabItem Header="Photo Preview" BorderBrush="#FFE8E8E8">
                <Grid>
                    <!--Two rows and two columns-->
                    <Grid.RowDefinitions>
                        <RowDefinition Height="50"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition Width="280"/>
                        <ColumnDefinition/>
                    </Grid.ColumnDefinitions>
                    <StackPanel Grid.ColumnSpan="2"  Orientation="Horizontal" Margin="0,2,0,2">

                        <TextBlock VerticalAlignment="Center" FontSize="16">Selected file:</TextBlock>
                        <TextBlock VerticalAlignment="Center" FontSize="16" Text="{Binding Model.SelectFileleName}"></TextBlock>
                    </StackPanel>
                    <TreeView Grid.Column="0" Grid.Row="1" x:Name="departmentTree" PreviewMouseUp="departmentTree_PreviewMouseUp">
                        <TreeView.ItemTemplate>
                            <HierarchicalDataTemplate ItemsSource="{Binding Subitem}">
                                <StackPanel  Orientation="Horizontal" Margin="0,2,0,2">
                                    <Image  Source="{Binding Icon,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></Image>
                                    <!--<Image  Source="../refresh/folder.ico"></Image>--> 
                                    <TextBlock VerticalAlignment="Center" FontSize="14" Text="{Binding FileName}" ToolTip="{Binding FilePath,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"></TextBlock>
                                    <TextBlock VerticalAlignment="Center" FontSize="14" Text="{Binding SubitemCount}" FontWeight="Bold"></TextBlock>
                                </StackPanel>
                            </HierarchicalDataTemplate>
                        </TreeView.ItemTemplate>
                    </TreeView>


                    <!--Photo-->
                    <Image Grid.Column="1" Grid.Row="1"  x:Name="MyImage"/>
                </Grid>

            </TabItem>
            <TabItem Header="Set up" Width="64" BorderBrush="#FFEEEEEE">

            </TabItem>

        </TabControl>


    </Grid>
</Window>

Event code of backend TreeView control

using System;
using System.Collections.Generic;
using System.IO;
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;
using TreeViewDemo.ViewModel;

namespace TreeViewDemo
{
    /// <summary>
    ///Interaction logic of MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        MainWindowViewModel viewModel = new MainWindowViewModel();
        List<FileTreeModel> fileTreeData = new List<FileTreeModel>();
        public MainWindow()
        {
            InitializeComponent();
        }
        /// <summary>
        ///Daily Photo statistics
        /// </summary>
        public static int total = 0;
        /// <summary>
        ///Get photo catalog collection
        /// </summary>
        /// <param name="dir"></param>
        /// <param name="d"></param>
        /// <returns></returns>
        public List<FileTreeModel> GetAllFiles(DirectoryInfo dir, FileTreeModel d)
        {
            List<FileTreeModel> FileList = new List<FileTreeModel>();
            FileInfo[] allFile = dir.GetFiles();
            total = allFile.Count();
            foreach (FileInfo fi in allFile)
                d.Subitem.Add(new FileTreeModel() { FileName = fi.Name, FilePath = fi.FullName, FileType = (int)FieleTypeEnum.Picture, Icon = "../refresh/picture.ico" });

            DirectoryInfo[] allDir = dir.GetDirectories();
            foreach (DirectoryInfo dif in allDir)
            {
                FileTreeModel fileDir = new FileTreeModel() { FileName = dif.Name, FilePath = dif.FullName, FileType = (int)FieleTypeEnum.Folder, Icon = "../refresh/folder.ico" };
                GetAllFiles(dif, fileDir);
                fileDir.SubitemCount = string.Format($"({total})");
                FileList.Add(fileDir);

            }
            return FileList;
        }
        /// <summary>
        ///Tab select event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.Source is TabControl)
            {
                if (e.AddedItems != null && e.AddedItems.Count > 0)
                {
                    if (e.AddedItems[0] is TabItem)
                    {
                        TabItem tabItem = e.AddedItems[0] as TabItem;
                        if (tabItem.Header.ToString() == "Weighing record")
                        {

                        }
                        if (tabItem.Header.ToString() == "Photo Preview")
                        { 
                            string dataDir = AppDomain.CurrentDomain.BaseDirectory + "ImageLogs\\";

                            fileTreeData = GetAllFiles(new System.IO.DirectoryInfo(dataDir), new FileTreeModel()).OrderByDescending(s=>s.FileName).ToList();
                            this.departmentTree.ItemsSource = fileTreeData;
                        }
                    }
                }
            }
        }
          
        /// <summary>
        ///File tree selection event
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void departmentTree_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (departmentTree.SelectedItem != null)
                {
                    FileTreeModel selectedTnh = departmentTree.SelectedItem as FileTreeModel;
                    viewModel.Model.SelectFileleName = selectedTnh.FileName;

                    if (selectedTnh.FileType == (int)FieleTypeEnum.Picture)
                    {
                        BitmapImage imagesouce = new BitmapImage();
                        imagesouce = new BitmapImage(new Uri(selectedTnh.FilePath));//Uri("picture path")
                        MyImage.Source = imagesouce.Clone();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
           

        } 
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // Bind data source
            this.DataContext = viewModel; 
        }


    }
}  

 

Code download address: https://download.csdn.net/download/qingchundaima/10671993

Posted by SoberDude on Mon, 30 Dec 2019 11:06:39 -0800