<Window x:Class="CollectionBinding.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:data="clr-namespace:ClassLibrary;assembly=ClassLibrary"
        xmlns:local="clr-namespace:CollectionBinding"
        Title="MainWindow" Height="449.904" Width="358.716">
    <Window.Resources>
        <local:ImageConverter x:Key="ImageConverter"></local:ImageConverter>
        <DataTemplate DataType="{x:Type data:Product}" x:Key="DefaultDataTemplate">
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding Path=CategoryID}" Value="19">
                    <Setter Property="ListBoxItem.Foreground" Value="Red"></Setter>
                </DataTrigger>
            </DataTemplate.Triggers>
            <Border Margin="3" BorderThickness="1" BorderBrush="SteelBlue" CornerRadius="4">
                <Grid Margin="3">
                    <Grid.RowDefinitions>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                    </Grid.RowDefinitions>
                    <TextBlock Margin="3" FontWeight="Bold" Text="{Binding Path=ModelNumber}"></TextBlock>
                    <TextBlock Grid.Row="1" Margin="3" FontWeight="Bold" Text="{Binding Path=ModelName}"></TextBlock>
                    <Image Grid.Row="2" Margin="3" Height="100" Width="100" Source="{Binding Path=ProductImage,Converter={StaticResource ImageConverter}}"></Image>
                </Grid>
            </Border>
        </DataTemplate>

        <DataTemplate DataType="{x:Type data:Product}" x:Key="HighLightDataTemplate">
            <DataTemplate.Triggers>
                <DataTrigger Binding="{Binding Path=CategoryID}" Value="19">
                    <Setter Property="ListBoxItem.Foreground" Value="Yellow"></Setter>
                </DataTrigger>
            </DataTemplate.Triggers>
            <Border Margin="3" BorderThickness="1" BorderBrush="SteelBlue" CornerRadius="4">
                <Grid Margin="3">
                    <Grid.RowDefinitions>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                        <RowDefinition></RowDefinition>
                    </Grid.RowDefinitions>
                    <TextBlock Margin="3" FontWeight="Bold" FontStyle="Italic" Text="{Binding Path=ModelNumber}"></TextBlock>
                    <TextBlock Grid.Row="1" FontStyle="Italic" Margin="3" FontWeight="Bold" Text="{Binding Path=ModelName}"></TextBlock>
                    <Image Grid.Row="2" Margin="3" Height="100" Width="100" Source="{Binding Path=ProductImage,Converter={StaticResource ImageConverter}}"></Image>
                </Grid>
            </Border>
        </DataTemplate>

        <local:ProductTemplateSelector PropertyToEvaluate="CategoryID" PropertyValueToHighLight="16" DefaultDataTemplate="{StaticResource DefaultDataTemplate}"
                                       HighLightDataTemplate="{StaticResource HighLightDataTemplate}"
                                       x:Key="TemplateSelector"></local:ProductTemplateSelector>

    </Window.Resources>
 
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
            <RowDefinition Height="*"></RowDefinition>
        </Grid.RowDefinitions>
        <ListBox Margin="3" Grid.Row="0" Name="lstProducts" Height="120" 
                 ScrollViewer.VerticalScrollBarVisibility="Visible" ItemTemplateSelector="{StaticResource TemplateSelector}">
           
            
        </ListBox>
        <StackPanel Margin="3" Grid.Row="1" Orientation="Horizontal" HorizontalAlignment="Right">
            <Button Margin="3" MinWidth="100" Name="btnGetProducts" Click="btnGetProducts_Click_1">GetProducts</Button>
        </StackPanel>
        <Grid Margin="3" Name="grid" Grid.Row="2" DataContext="{Binding ElementName=lstProducts,Path=SelectedItem}">
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
                <RowDefinition Height="*"></RowDefinition>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="Auto"></ColumnDefinition>
                <ColumnDefinition></ColumnDefinition>
            </Grid.ColumnDefinitions>
            <TextBlock Margin="3" Grid.Row="0" Grid.Column="0">CategoryID:</TextBlock>
            <TextBox Name="txtCategoryID" Margin="3" Grid.Row="0" Grid.Column="1" Text="{Binding Path=CategoryID}"></TextBox>

            <TextBlock Margin="3" Grid.Row="1" Grid.Column="0">ModelNumber:</TextBlock>
            <TextBox Name="txtModelNumber" Margin="3" Grid.Row="1" Grid.Column="1" Text="{Binding Path=ModelNumber}"></TextBox>

            <TextBlock Margin="3" Grid.Row="2" Grid.Column="0">ModelName:</TextBlock>
            <TextBox Name="txtModelName" Margin="3" Grid.Row="2" Grid.Column="1" Text="{Binding Path=ModelName}"></TextBox>

            <TextBlock Margin="3" Grid.Row="3" Grid.Column="0">ProductImage:</TextBlock>
            <TextBox Name="txtProductImage" Margin="3" Grid.Row="3" Grid.Column="1" Text="{Binding Path=ProductImage}"></TextBox>

            <TextBlock Margin="3" Grid.Row="4" Grid.Column="0">UnitCost:</TextBlock>
            <TextBox Name="txtUnitCost" Margin="3" Grid.Row="4" Grid.Column="1" Text="{Binding Path=UnitCost}">
                
            </TextBox>
            
            <TextBox Name="txtDescription" Margin="3" Grid.Row="5" Grid.Column="0" Grid.ColumnSpan="2" TextWrapping="Wrap"
                     Text="{Binding Path=Description}" ScrollViewer.VerticalScrollBarVisibility="Visible"></TextBox>
        </Grid>
    </Grid>

</Window>

using ClassLibrary;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
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 CollectionBinding
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        public ObservableCollection<Product> products;

        private void btnGetProducts_Click_1(object sender, RoutedEventArgs e)
        {
            products = StoreDB.GetProducts();
            lstProducts.ItemsSource = products;
        }

    }

}

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 ClassLibrary
{
    public class StoreDB
    {
        public static string connString = Properties.Settings.Default.ConnectionString;

        public static Product GetProductByID(int id)
        {
            Product p = null;
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("GetProductByID", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@ProductID", id);
            try
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    p = new Product()
                    {
                        CategoryID = (int)reader[1],
                        ModelNumber = reader[2].ToString(),
                        ModelName = reader[3].ToString(),
                        ProductImage=reader[4].ToString(),
                        UnitCost = (decimal)reader[5],
                        Description = reader[6].ToString()
                    };
                }
                return p;

            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                con.Close();
            }
        }

        public static void UpdateProductByID(int ProductID,Product p)
        {
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("UpdateProductByID", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@ProductID",ProductID);
            cmd.Parameters.AddWithValue("@CategoryID",p.CategoryID);
            cmd.Parameters.AddWithValue("@ModelNumber",p.ModelNumber);
            cmd.Parameters.AddWithValue("@ModelName",p.ModelName);
            cmd.Parameters.AddWithValue("@ProductImage",p.ProductImage);
            cmd.Parameters.AddWithValue("@UnitCost",p.UnitCost);
            cmd.Parameters.AddWithValue("@Description",p.Description);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                con.Close();
            }
        }

        public static void InsertProduct(Product p)
        {
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("InsertProduct", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@CategoryID", p.CategoryID);
            cmd.Parameters.AddWithValue("@ModelNumber", p.ModelNumber);
            cmd.Parameters.AddWithValue("@ModelName", p.ModelName);
            cmd.Parameters.AddWithValue("@ProductImage", p.ProductImage);
            cmd.Parameters.AddWithValue("@UnitCost", p.UnitCost);
            cmd.Parameters.AddWithValue("@Description", p.Description);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                con.Close();
            }
        }

        public static void DeleteProductByID(int id)
        {
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("DeleteProductByID", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@ProductID", id);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception)
            {

                throw;
            }
            finally
            {
                con.Close();
            }
        }

        public static ObservableCollection<Product> GetProducts()
        {
            ObservableCollection<Product> products = new ObservableCollection<Product>();
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("GetProducts", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            try
            {
                con.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                while (reader.Read())
                {
                    products.Add(new Product()
                    {
                        ProductID = (int)reader[0],
                        CategoryID = (int)reader[1],
                        ModelNumber = reader[2].ToString(),
                        ModelName = reader[3].ToString(),
                        ProductImage = reader[4].ToString(),
                        UnitCost = (decimal)reader[5],
                        Description = reader[6].ToString()
                    });
                }
                return products;

            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                con.Close();
            }
        }

        public static DataSet GetProductsAndCategories()
        {
            SqlConnection con = new SqlConnection(connString);
            SqlCommand cmd = new SqlCommand("GetProducts", con);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            DataSet ds = new DataSet();
            SqlDataAdapter adatper = new SqlDataAdapter(cmd);
            adatper.Fill(ds, "Products");
            cmd.CommandText = "GetCategories";
            adatper.Fill(ds, "Categories");
            DataRelation rel = new DataRelation("CategoryProduct", ds.Tables["Categories"].Columns["CategoryID"], ds.Tables["Products"].Columns["CategoryID"]);
            return ds;
        }
    }

}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary
{
    public class Product
    {
        public int ProductID { get; set; }
        public int CategoryID { get; set; }
        public string ModelNumber { get; set; }
        public string ModelName { get; set; }
        public string ProductImage { get; set; }
        public decimal UnitCost { get; set; }
        public string Description { get; set; }

        public Product(int CategoryID = 0, string ModelNumber = "",
            string ModelName = "", string ProductImage = "", decimal UnitCost=0,string Description="")
        {
            this.CategoryID = CategoryID;
            this.ModelNumber = ModelNumber;
            this.ModelName = ModelName;
            this.ProductImage = ProductImage;
            this.UnitCost = UnitCost;
            this.Description = Description;
        }

    }

}

using ClassLibrary;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;

namespace CollectionBinding
{
    public class ProductTemplateSelector:DataTemplateSelector
    {
        public DataTemplate DefaultDataTemplate { get; set; }

        public DataTemplate HighLightDataTemplate { get; set; }

        public string PropertyToEvaluate { get; set; }
        public string PropertyValueToHighLight { get; set; }

        public override System.Windows.DataTemplate SelectTemplate(object item, System.Windows.DependencyObject container)
        {
            Product p = (Product)item;
            Type type = p.GetType();
            PropertyInfo pi = type.GetProperty(PropertyToEvaluate);
            if (pi.GetValue(p, null).ToString() == PropertyValueToHighLight)
            {
                return HighLightDataTemplate;
            }
            else
            {
                return DefaultDataTemplate;
            }
        }
    }
}

WPF DataTemplateSelector的使用的更多相关文章

  1. WPF:DataTemplateSelector设置控件不同的样式

    原文 WPF:DataTemplateSelector设置控件不同的样式 最近想实现这么个东西,一个ListBox, 里面的ListBoxItem可能是文本框.下拉框.日期选择控件等等. 很自然的想到 ...

  2. WPF之DataTemplateSelector技巧

    WPF中如何通过一个属性来控制对象的模板,属性值改变时对象的模板会跟随改变? 两个关键点   1 属性/对象更改通知 方法一:继承INotifyPropertyChanged接口,当属性值更改时需要让 ...

  3. wpf 模板选择器DataTemplateSelector及动态绑定使用教程

    其实也说不上算是教程了,只是把自己学习的代码拿出来分享一下,同时方便以后遇到类似问题的时候翻一下.MSDN里如是说:通常,如果有多个 DataTemplate 可用于同一类型的对象,并且您希望根据每个 ...

  4. WPF之DataTemplateSelector的运用

    本文主要记录WPF中DataTemplateSelector的运用,数据模板选择器主要运用在一些项容器中用于根据不同的数据类型选择不同的DataTemplate,以便展示不同的数据.在此以在listb ...

  5. WPF中DataTemplateSelector的简单应用

    WPF中DataTemplateSelector的简单应用 DataTemplateSelector中文叫数据模板选择器,根据数据模型内的属性值选择不同的数据模板,多用于容器如listbox中,达到同 ...

  6. 【转】wpf 模板选择器DataTemplateSelector及动态绑定,DataTemplate.Triggers触发器的使用

    通常,如果有多个 DataTemplate 可用于同一类型的对象,并且您希望根据每个数据对象的属性提供自己的逻辑来选择要应用的 DataTemplate,则应创建 DataTemplateSelect ...

  7. wpf 模板选择器DataTemplateSelector及动态绑定,DataTemplate.Triggers触发器的使用

    通常,如果有多个 DataTemplate 可用于同一类型的对象,并且您希望根据每个数据对象的属性提供自己的逻辑来选择要应用的 DataTemplate,则应创建 DataTemplateSelect ...

  8. WPF 中关于 DataTemplateSelector 类的应用

    MSDN的解释: 提供一种根据数据对象和与该数据绑定的元素来选择数据模板 DataTemplate 的方法. 示例代码: <Window x:Class="WpfApplication ...

  9. WPF/UWP 模板选择器 DataTemplateSelector

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...

随机推荐

  1. javascript数组全排列,数组元素所有组合

    function permute(input) { var permArr = [], usedChars = []; function main(input){ var i, ch; for (i ...

  2. Net Reactor 5

    Net Reactor 5脱壳教程   今天别人发来一个.Net的DLL让我脱壳,第一步自然是先扔进de4dot 我这个de4dot 是集成了  Ivancito0z / TheProxy / PC- ...

  3. Codeforces 491B. New York Hotel 最远曼哈顿距离

    最远曼哈顿距离有两个性质: 1: 对每一个点(x,y)  分别计算  +x+y , -x+y , x-y , -x-y 然后统计每种组合的最大值就能够了, 不会对结果产生影响 2: 去掉绝对值 , 设 ...

  4. android WebView总 结

    浏览器控件是每个开发环境都具备的,这为马甲神功提供了用武之地,windows的有webbrowser,android和ios都有webview.只是其引擎不同,相对于微软的webbrowser,and ...

  5. 【codeforces 757A】Gotta Catch Em' All!

    time limit per test1 second memory limit per test256 megabytes inputstandard input outputstandard ou ...

  6. [NPM] Pull out npm scripts into another file with p-s

    A technique you might use once you start having lots of npm scripts is to use a node package that al ...

  7. NOIP 模拟 box - 费用流 / 匈牙利

    题目大意: 给出n(\(\le 200\))个盒子,第i个盒子长\(x_i\),宽\(y_i\),一个盒子可以放入长宽都大于等于它的盒子里,并且每个盒子里只能放入一个盒子(可以嵌套),嵌套的盒子的占地 ...

  8. BZOJ 3932 - 主席树

    传送门 题目分析 在只打会主席树模板的情况下做了这道题,也算是深有体会. 首先任务可以差分:一个任务是(s, e, p), 则在s处+1, 在e+1处-1,符合前缀.但是我们要查询指定时间的前k任务之 ...

  9. 微信Android终端SDK新手使用指南

    1.申请你的AppID 请到 开发者应用登记页面 进行登记,登记并选择移动应用进行设置后,将获得AppID,可立即用于开发.但应用登记完成后还需要提交审核,只有审核通过的应用才能正式发布使用. 2.下 ...

  10. 远程ssh执行命令时提示找不到命令

    最开始的时候碰到这种问题,是在hadoop003上配置了jdk1.8, 在hadoop002上执行ssh hadoop003 java -version提示没有命令,先ssh hadoop003然后执 ...