WPF DataTemplateSelector的使用
<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的使用的更多相关文章
- WPF:DataTemplateSelector设置控件不同的样式
原文 WPF:DataTemplateSelector设置控件不同的样式 最近想实现这么个东西,一个ListBox, 里面的ListBoxItem可能是文本框.下拉框.日期选择控件等等. 很自然的想到 ...
- WPF之DataTemplateSelector技巧
WPF中如何通过一个属性来控制对象的模板,属性值改变时对象的模板会跟随改变? 两个关键点 1 属性/对象更改通知 方法一:继承INotifyPropertyChanged接口,当属性值更改时需要让 ...
- wpf 模板选择器DataTemplateSelector及动态绑定使用教程
其实也说不上算是教程了,只是把自己学习的代码拿出来分享一下,同时方便以后遇到类似问题的时候翻一下.MSDN里如是说:通常,如果有多个 DataTemplate 可用于同一类型的对象,并且您希望根据每个 ...
- WPF之DataTemplateSelector的运用
本文主要记录WPF中DataTemplateSelector的运用,数据模板选择器主要运用在一些项容器中用于根据不同的数据类型选择不同的DataTemplate,以便展示不同的数据.在此以在listb ...
- WPF中DataTemplateSelector的简单应用
WPF中DataTemplateSelector的简单应用 DataTemplateSelector中文叫数据模板选择器,根据数据模型内的属性值选择不同的数据模板,多用于容器如listbox中,达到同 ...
- 【转】wpf 模板选择器DataTemplateSelector及动态绑定,DataTemplate.Triggers触发器的使用
通常,如果有多个 DataTemplate 可用于同一类型的对象,并且您希望根据每个数据对象的属性提供自己的逻辑来选择要应用的 DataTemplate,则应创建 DataTemplateSelect ...
- wpf 模板选择器DataTemplateSelector及动态绑定,DataTemplate.Triggers触发器的使用
通常,如果有多个 DataTemplate 可用于同一类型的对象,并且您希望根据每个数据对象的属性提供自己的逻辑来选择要应用的 DataTemplate,则应创建 DataTemplateSelect ...
- WPF 中关于 DataTemplateSelector 类的应用
MSDN的解释: 提供一种根据数据对象和与该数据绑定的元素来选择数据模板 DataTemplate 的方法. 示例代码: <Window x:Class="WpfApplication ...
- WPF/UWP 模板选择器 DataTemplateSelector
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
随机推荐
- [React Unit Testing] React unit testing demo
import React from 'react' const Release = React.createClass({ render() { const { title, artist, outO ...
- Shuttle ESB(三)——架构模型介绍(2)
上一篇文章中,介绍了Shuttle ESB架构模型中的三个重要部分. 今天,我们继续介绍剩余的三个内容:模式和消息路由. 四.模式 Request/Response(请求/响应模式) 对基于Reque ...
- spring+aspectJ的实现
AspectJ:(Java社区里最完整最流行的AOP框架) spring自身也有一套AOP框架,但相比较于AspectJ,更推荐AspectJ 在Spring2.0以上版本中,可以使用基于Aspect ...
- (ubuntu 下)tensorflow 的安装及版本升级
对于 CPU 版本 pip3 install –upgrade tensorflow 对于 GPU 版本: pip3 install –upgrade tensorflow-gpu [TensorFl ...
- [GeekBand] 设计模式之观察者模式学习笔记
本文参考文献::GeekBand课堂内容,授课老师:李建忠 :网络资料: http://blog.csdn.net/hguisu/article/details/7556625 本文仅作为自己的学习笔 ...
- CentOS7 下的mysql安装与配置
之前虽然也安装过多次mysql,但每次都会遇到各种小问题,这次记录下来,以备后查. 首先是下载与安装 # wget http://dev.mysql.com/get/mysql-community-r ...
- C#性能优化:延迟初始化Lazy
1. 概述 我们创建某一个对象需要很大的消耗,而这个对象在运行过程中又不一定用到,为了避免每次运行都创建该对象,这时候延迟初始化(也叫延迟实例化)就出场了. 延迟初始化出现于.NET 4.0,主要用于 ...
- instsrv.exe用法
这个小工具是用以安装和卸载可执行的服务和指派服务名给这些可执行的服务的. 一:绑定程序和服务 这里我们设定要将F:\cpu.exe 以 abc 的名称显示作为服务的话,我们应当这样子做: 在开 ...
- js限制文本框input只能输入数字
JS判断只能是数字和小数点. ,文本框只能输入数字代码(小数点也不能输入) 复制代码 代码示例:<input onkeyup="this.value=this.value.replac ...
- 图像块的访问(填充 padding,步长 stride,窗 Window/kernel/filter)
无填充是有填充的特例(填充为 1). utilities(matlab)-- 图像分块(image2cols.cols2image)(未填充) 1. 一个图像块 ⇒ 返回一个值 输出矩阵的大小: ou ...