WPF中TreeView控制項的使用案例

来源:https://www.cnblogs.com/wendj/archive/2018/09/18/9667122.html
-Advertisement-
Play Games

WPF總體來說還是比較方便的,其中變化最大的主要是Listview和Treeview控制項,而且TreeView似乎在WPF是一個備受指責的控制項,很多人說他不好用。我這個demo主要是在wpf中使用TreeView控制項實現圖片查看功能,簡單的Grid佈局、TreeView控制項添加圖標、TreeView ...


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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • import shutil 高級的文件,文件夾,壓縮包的處理模塊,也主要用於文件的拷貝 shutil.copyfileobj(fsrc,fdst[,length]): 將文件的內容拷貝到另一個文件(可以指定length長度進行拷貝) shutil.copyfile(src,dst): 拷貝文件 sh ...
  • 希臘字母 |字母名稱 |大寫 | 小寫 | 大寫latex| 小寫latex| |字母名稱 |大寫 | 小寫 | 大寫latex| 小寫latex| | : : |: : | : : | : : | : : | |alpha| A | $\alpha$ | | \alpha ||xi | $\Xi$ ...
  • 1、索引:索引就是數據表中數據和響應的存儲位置的列表,利用索引可以提高在表或視圖中的查找數據的速度 2、索引分類:聚集索引和非聚集索引 1、唯一索引(如果有主鍵,那麼主鍵就是唯一索引) 2、索引視圖 3、全文索引 4、xml索引等等 3、語法: 4、為什麼使用索引 索引是一個單獨的、存儲在磁碟上的數 ...
  • var list1 = new List<int> { 1, 3, 5, 7, 9, 11, 13, 15 }; var list2 = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // List1:1 3 5 7 9 11 13 15 Console. ...
  • 一、前言 1、本文主要內容 Visual Studio Code 開發環境配置 使用 ASP.NET Core 構建Web應用 ASP.NET Core Web 應用啟動類說明 ASP.NET Core Web 項目結構說明 2、本教程環境信息 3、前置知識 你可能需要的前置知識 VS Code + ...
  • C# GetHashCode、Equals函數和鍵值對集合的關係 說明 HashCode:Hash碼。特性:兩個值,相同的的值生成的Hash肯定相同,但是不同的值生成的Hash很大程式上會不同。作用:求Hash值效率比引用類型判斷是否相等的函數Equals更快,所以被用來輔助判斷鍵值對集合的鍵值是否 ...
  • EF中的FluentApi作用是通過配置領域類來覆蓋預設的約定。在EF中,我們通過DbModelBuilder類來使用FluentApi,它的功能比數據註釋屬性更強大。 使用FluentApi時,我們在context類的OnModelCreating()方法中重寫配置項,一個慄子: 我們可以把Flu ...
  • 作為一個優秀的開源調度框架,Quartz 具有以下特點: 另外,作為 Spring 預設的調度框架,Quartz 很容易與 Spring 集成實現靈活可配置的調度功能。 quartz調度核心元素: 我這裡簡單記錄使用過程及代碼: 1:首先引用Quartz組件 2:using Quartz;using ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...