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 ...
随机推荐
- 域名从www跳转到非www,Apache和Nginx2种解决方式
背景:www跳转到非www. http://www.jiutianniao.com和http://jiutianniao.com 都可以访问. 但是,想把www这个重定向到非www,输入更简单,让搜 ...
- 手动打war包进行部署测试
有的时候项目跑不起来但是又不知道tomcat问题还是其他问题,往往新建个项目,打成war进行部署.今天找到个好方法,手动打成war,然后进行部署测试. image.png image.png 创建一个 ...
- Spring mvc 多文件上传
http://blog.csdn.net/swingpyzf/article/details/20230865
- PHP移动互联网开发笔记(7)——MySQL数据库基础回顾[1]
一.数据类型 1.整型 数据类型 存储空间 说明 取值范围 TINYINT 1字节 非常小的整数 带符号值:-128~127无符号值:0~255 SMALLINT 2字节 较小的整数 带符号值:-32 ...
- 不使用left-join等多表关联查询,只用单表查询和Java程序,简便实现“多表查询”效果
上次我们提到,不使用left-loin关联查询,可能是为了提高效率或者配置缓存,也可以简化一下sql语句的编写.只写单表查询,sql真得太简单了.问题是,查询多个表的数据还是非常需要的. 因此,存在这 ...
- AR Drone系列之:使用ROS catkin创建package并使用cv_bridge实现对ar drone摄像头数据的处理
1 开发环境 Ubuntu 12.04 ROS Hydro 2 前提 可參考这篇blog:http://blog.csdn.net/yake827/article/details/44564057 b ...
- C#委托之个人理解
C#委托之个人理解 什么是委托 首先要知道什么是委托,用最通俗易懂的话来讲,你就可以把委托看成是用来执行方法(函数)的一个东西. 如何使用委托 在使用委托的时候,你可以像对待一个类一样对待它.即先 ...
- Linux SVNserver建立
1. Ubuntu PC一个.最好是最新的Ubuntu稳定的版本号 2. 运行以下命令来安装subversion: sudo apt-get update sudo apt-get install s ...
- 【cocos2dx 加载资源目录】
从互联网下载vsproject代码.编译一切都还好吗,当发现向导的最后一个执行create没有找到图片功能异常.看图片Resource的内容下表,他没有排除的图像的可能性. 那么之后呢?!仅仅能是pr ...
- android中滑动SQLite数据库分页加载
今天用到了android中滑动SQlit数据库分页加载技术,写了个测试工程,将代码贴出来和大家交流一下: MainActivity package com.example.testscrollsqli ...