码迷,mamicode.com
首页 > Windows程序 > 详细

WPF中TreeView控件的使用案例

时间:2018-09-18 19:16:55      阅读:297      评论:0      收藏:0      [点我收藏+]

标签:tostring   地址   目录   添加图标   nts   down   后端   model   添加   

WPF总体来说还是比较方便的,其中变化最大的主要是Listview和Treeview控件,而且TreeView似乎在WPF是一个备受指责的控件,很多人说他不好用。我这个demo主要是在wpf中使用TreeView控件实现图片查看功能,简单的Grid布局、TreeView控件添加图标、TreeView控件的一些事件、显示统计、还有就是读取文件操作。

效果图:

技术分享图片

前端主要代码:

<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中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="照片预览" BorderBrush="#FFE8E8E8">
                <Grid>
                    <!--两行两列-->
                    <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">选中文件:</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>


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

            </TabItem>
            <TabItem Header="设置" Width="64" BorderBrush="#FFEEEEEE">

            </TabItem>

        </TabControl>


    </Grid>
</Window>

 后端TreeView控件事件代码

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>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        MainWindowViewModel viewModel = new MainWindowViewModel();
        List<FileTreeModel> fileTreeData = new List<FileTreeModel>();
        public MainWindow()
        {
            InitializeComponent();
        }
        /// <summary>
        /// 每一天照片统计
        /// </summary>
        public static int total = 0;
        /// <summary>
        /// 获取照片目录集合
        /// </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选择事件
        /// </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() == "过磅记录")
                        {

                        }
                        if (tabItem.Header.ToString() == "照片预览")
                        { 
                            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>
        /// 文件树选中事件
        /// </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("图片路径")
                        MyImage.Source = imagesouce.Clone();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
           

        } 
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            // 绑定数据源
            this.DataContext = viewModel; 
        }


    }
}  

 

代码下载地址:https://download.csdn.net/download/qingchundaima/10671993

WPF中TreeView控件的使用案例

标签:tostring   地址   目录   添加图标   nts   down   后端   model   添加   

原文地址:https://www.cnblogs.com/wendj/p/9667122.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!