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 ...
随机推荐
- 【34.25%】【BZOJ 2648】SJY摆棋子
Time Limit: 20 Sec Memory Limit: 128 MB Submit: 2718 Solved: 931 [Submit][Status][Discuss] Descrip ...
- 【37.21%】【codeforces 721B】Passwords
time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...
- nyoj 949哈利波特(细节题)
哈利波特 时间限制:1000 ms | 内存限制:65535 KB 难度:3 描写叙述 Harry 新学了三种魔法.他能够用第一种魔法把 a 克的沙子变成 b 克金属,能够用另外一种魔法把 c 克 ...
- 《Kinect应用开发实战》读书笔记---干货集合
本文章由cartzhang编写,转载请注明出处. 所有权利保留. 文章链接: http://blog.csdn.net/cartzhang/article/details/45029841 作者:ca ...
- Atom编辑器折腾记_(13)JS代码智能提示补全(插件:atom-ternjs)
题外话 官方正式版尽管内置了.autocomplete-plus;最为明显的一个功能就是记忆你已经输入过的名称进行匹配; 可是针对于某些语言来说,还是有些不足的-.当中JS的补全上就明显不足了-所以须 ...
- 路由(Routing)
RabbitMQ系列教程之四:路由(Routing) (使用Net客户端) 在上一个教程中,我们构建了一个简单的日志系统,我们能够向许多消息接受者广播发送日志消息. 在本教程中,我们将为其添加一项功能 ...
- [转至云风的博客]谈谈陌陌争霸在数据库方面踩过的坑( Redis 篇)
« 谈谈陌陌争霸在数据库方面踩过的坑(芒果篇) | 返回首页 | linode 广告时间 » 谈谈陌陌争霸在数据库方面踩过的坑( Redis 篇) 注:陌陌争霸的数据库部分我没有参与具体设计,只是参与 ...
- 小强的HTML5移动开发之路(26)—— JavaScript回顾1
很久没有怎么用过JavaScript了,感觉有点生疏,最近在看关于HTML5移动开发方面的资料,有一种直觉告诉我,JavaScript昨天.今天很重要,明天会更重要.现在好多基于JavaScript的 ...
- CF337D Book of Evil - 树型dp
传送门 题目大意: 一棵树上有一个特殊点,特殊点可以影响距离小于等于d的点,现在告诉被影响的点,问特殊点可以在几个点上. 题目分析: 对题意进行转化:求到被影响点的最大距离小于等于d的点数目. 然后就 ...
- Windows应用程序的消息处理机制
(1)操作系统接收到应用程序的窗体消息,将消息投递到该应用程序的消息队列中. (2)应用程序在消息循环中调用GetMessage函数从消息队列中取出一条一条的消息. 取出消息后,应用程序能够对消息进行 ...