方法一

<Window x:Class="TreeViewDemo.MainWindow"

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525" >
    <Grid>
        <TreeView Name="TreeCategories" Margin="5">
            <TreeView.ItemTemplate>
                <HierarchicalDataTemplate ItemsSource="{Binding Path=Products}">
                    <TextBlock Text="{Binding Path=CategoryName}"></TextBlock>
                    <HierarchicalDataTemplate.ItemTemplate>
                        <DataTemplate>
                            <TextBlock Text="{Binding Path=ModelName}"></TextBlock>
                        </DataTemplate>
                    </HierarchicalDataTemplate.ItemTemplate>
                </HierarchicalDataTemplate>
            </TreeView.ItemTemplate>
        </TreeView>
    </Grid>

</Window>

方法二

<Window x:Class="TreeViewDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DBAccess;assembly=DBAccess"
        Title="MainWindow" Height="350" Width="525" >
    <Window.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Category}" ItemsSource="{Binding Path=Products}">
            <TextBlock Text="{Binding Path=CategoryName}"></TextBlock>
        </HierarchicalDataTemplate>
        
        <HierarchicalDataTemplate DataType="{x:Type local:Product}">
            <TextBlock Text="{Binding Path=ModelName}"></TextBlock>
        </HierarchicalDataTemplate>
    </Window.Resources>
    <Grid>
        <TreeView Name="TreeCategories" Margin="5">
            
        </TreeView>
    </Grid>
</Window>

using DBAccess;
using System;
using System.Collections.Generic;
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;

namespace TreeViewDemo
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            TreeCategories.ItemsSource = StoreDB.GetCategoriedAndProducts();
        }
    }

}

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DBAccess
{
    public class StoreDB
    {
        public static string connStr = Properties.Settings.Default.Store;

        public static ObservableCollection<Product> GetProducts()
        {
            ObservableCollection<Product> products = new ObservableCollection<Product>();
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                SqlCommand cmd = new SqlCommand("GetProducts", conn);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    products.Add(new Product((int)reader["ProductID"],(int)reader["CategoryID"],reader["ModelNumber"].ToString(),
                        reader["ModelName"].ToString(),reader["ProductImage"].ToString(),(decimal)reader["UnitCost"],reader["Description"].ToString()));
                }

                return products;
            }
        }

        public static Product GetProductByID(int ProductID)
        {
            Product pro =null;
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                SqlCommand cmd = new SqlCommand("GetProductByID", conn);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@ProductID",ProductID));
                conn.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    pro = new Product((int)reader["ProductID"], (int)reader["CategoryID"], reader["ModelNumber"].ToString(),
                        reader["ModelName"].ToString(), reader["ProductImage"].ToString(), (decimal)reader["UnitCost"], reader["Description"].ToString());
                }

                return pro;
            }
        }

        public static bool UpdateProduct(Product pro)
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                SqlCommand cmd = new SqlCommand("UpdateProductByID", conn);
                cmd.CommandType = System.Data.CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter("@ProductID", pro.ProductID));
                cmd.Parameters.Add(new SqlParameter("@ModelName", pro.ModelName));
                cmd.Parameters.Add(new SqlParameter("@ModelNumber", pro.ModelNumber));
                cmd.Parameters.Add(new SqlParameter("@UnitCost", pro.UnitCost));
                cmd.Parameters.Add(new SqlParameter("@Description", pro.Description));

                conn.Open();
                return cmd.ExecuteNonQuery() > 0;
                
            }
        }

        public static DataTable GetProductsDataTable()
        {
            using(SqlConnection conn = new SqlConnection(connStr))
            {
                SqlCommand cmd = new SqlCommand("GetProducts", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapter.Fill(ds, "Products");
                return ds.Tables["Products"];
            }
        }

        public static DataSet GetCategoriedAndProductsDataSet()
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                SqlCommand cmd = new SqlCommand("GetProducts", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapter.Fill(ds, "Products");

                cmd.CommandText = "GetCategories";
                adapter.Fill(ds, "Categories");

                DataRelation dr = new DataRelation("CategoryProduct", ds.Tables["Categories"].Columns["CategoryID"], ds.Tables["Produdcts"].Columns["CategoryID"]);
                ds.Relations.Add(dr);
                return ds;
            }
        }

        public static ICollection<Category> GetCategoriedAndProducts()
        {
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                SqlCommand cmd = new SqlCommand("GetProducts", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                SqlDataAdapter adapter = new SqlDataAdapter(cmd);
                DataSet ds = new DataSet();
                adapter.Fill(ds, "Products");

                cmd.CommandText = "GetCategories";
                adapter.Fill(ds, "Categories");

                DataRelation dr = new DataRelation("CategoryProduct", ds.Tables["Categories"].Columns["CategoryID"], ds.Tables["Products"].Columns["CategoryID"]);
                ds.Relations.Add(dr);
                ObservableCollection<Category> categories = new ObservableCollection<Category>();
                foreach (DataRow categoryRow in ds.Tables["Categories"].Rows)
                {
                    ObservableCollection<Product> products = new ObservableCollection<Product>();
                    foreach (DataRow productRow in categoryRow.GetChildRows(dr))
                    {
                        products.Add(new Product((int)productRow["ProductID"],(int)productRow["CategoryID"],productRow["ModelNumber"].ToString(),productRow["ModelName"].ToString(),productRow["ProductImage"].ToString(),(decimal)productRow["UnitCost"],productRow["Description"].ToString()));
                        
                    }
                    categories.Add(new Category(categoryRow["CategoryName"].ToString(),products));
                }

                return categories;
                
            }
        }
    }
}

WPF TreeView绑定xaml的写法的更多相关文章

  1. WPF TreeView绑定字典集合

    <TreeView Name="Tree" HorizontalAlignment="Left" Height="269" Width ...

  2. 整理:WPF中Xaml中绑定枚举的写法

    原文:整理:WPF中Xaml中绑定枚举的写法 目的:在Combobox.ListBox中直接绑定枚举对象的方式,比如:直接绑定字体类型.所有颜色等枚举类型非常方便 一.首先用ObjectDataPro ...

  3. 整理:WPF用于绑定命令和触发路由事件的自定义控件写法

    原文:整理:WPF用于绑定命令和触发路由事件的自定义控件写法 目的:自定义一个控件,当点击按钮是触发到ViewModel(业务逻辑部分)和Xaml路由事件(页面逻辑部分) 自定义控件增加IComman ...

  4. 学习WPF——了解WPF中的XAML

    XAML的简单说明 XAML是用于实例化.NET对象的标记语言,主要用于构建WPF的用户界面 XAML中的每一个元素都映射为.NET类的一个实例,例如<Button>映射为WPF的Butt ...

  5. WPF多路绑定

    WPF多路绑定 多路绑定实现对数据的计算,XAML:   引用资源所在位置 xmlns:cmlib="clr-namespace:CommonLib;assembly=CommonLib&q ...

  6. WPF中 PropertyPath XAML 语法

    原文:WPF中 PropertyPath XAML 语法 PropertyPath 对象支持复杂的内联XAML语法用来设置各种各样的属性,这些属性把PropertyPath类型作为它们的值.这篇文章讨 ...

  7. WPF元素绑定

    原文:WPF元素绑定 数据绑定简介:数据绑定是一种关系,该关系告诉WPF从源对象提取一些信息,并用这些信息设置目标对象的属性.目标属性是依赖项属性.源对象可以是任何内容,从另一个WPF元素乃至ADO. ...

  8. WPF TreeView HierarchicalDataTemplate

    原文 WPF TreeView HierarchicalDataTemplate HierarchicalDataTemplate 的DataType是本层的绑定,而ItemsSource是绑定下层的 ...

  9. 【广州.NET社区推荐】【译】Visual Studio 2019 中 WPF & UWP 的 XAML 开发工具新特性

    原文 | Dmitry 翻译 | 郑子铭 自Visual Studio 2019推出以来,我们为使用WPF或UWP桌面应用程序的XAML开发人员发布了许多新功能.在本周的 Visual Studio ...

随机推荐

  1. Ubuntu10.04下安装Qt4和创建第一个Qt程序

    1.首先安装Qt4并采用Qt Creator进行开发演示 (1)在Terminal中输入: sudo apt-get install qt4-dev-tools qt4-doc qt4-qtconfi ...

  2. jquery ajax跨域 thinkphp getjson

    jquery中post的应该是不能跨域,网上说get的可以跨域,但是我试了一下也不行,然后就进行最后的拼搏getjson,结果成功,哈哈 js处写作 $.getJSON( "/index.p ...

  3. Spring-boot更改成war包的方式

    转载至:  https://blog.csdn.net/zhuwei_clark/article/details/82114102  Step1 修改启动类 Step2 修改配置文件为properti ...

  4. 基于bootstrap的富文本框——wangEditor【欢迎增加开发】

    先来一张效果图: 01. 引言 老早就開始研究富文本框的东西,在写完<深入理解javascript原型与闭包>之后,就想着要去做一个富文本框的插件的样例. 如今网络上开源的富文本框插件许多 ...

  5. Android 用LinkedList实现队列

    队列 队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作.进行插入操作的端称为队尾,进行删除操作的端称为队头.队列中没有元素时,称为空队列. 在 ...

  6. Local database deployment problems and fixtures

    /*By Jiangong SUN*/ After encountering some problems in deploying databases to local server, here ar ...

  7. [Angular] Using the platform agnostic Renderer & ElementRef

    ElementRef: ElementRef is a way to access native html element, notice that it only works for Broswer ...

  8. 小强的HTML5移动开发之路(37)——jqMobi快速入门

    在<小强的HTML5移动开发之路(33)-- jqMobi基础>中我们了解了什么是jqMobi,并从官方下载了jqMobi开发包,下载后解压目录如下: 拷贝上面的/css目录./plugi ...

  9. c++ try catch 问题(没有throw就会被删除,加上/EHa这样就不会被删除)

    以前都是用try{} catch(…){}来捕获C++中一些意想不到的异常, 今天看了Winhack的帖子才知道,这种方法在VC中其实是靠不住的.例如下面的代码: 以前都是用try{} catch(… ...

  10. Erlang 转至维基百科

    Erlang(英语发音:/ˈɜrlæŋ/)是一种通用的并行程序设计语言,它由乔·阿姆斯特朗(Joe Armstrong)在瑞典电信设备制造商爱立信所辖的计算机科学研究室开发,目的是创造一种可以应付大规 ...