欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WPF中TreeView控件的使用案例

程序员文章站 2024-02-01 20:20:52
WPF总体来说还是比较方便的,其中变化最大的主要是Listview和Treeview控件,而且TreeView似乎在WPF是一个备受指责的控件,很多人说他不好用。我这个demo主要是在wpf中使用TreeView控件实现图片查看功能,简单的Grid布局、TreeView控件添加图标、TreeView ......

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

效果图:

WPF中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; 
        }


    }
}  

 

代码下载地址: