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 ...
随机推荐
- [RxJS] Use RxJS concatMap to map and concat high order observables
Like switchMap and mergeMap, concatMap is a shortcut for map() followed by a concatAll(). In this le ...
- 指针知识梳理6-const与指针
const 定义的变量为仅仅读变量.在语法层面上通过这个变量去改动内存是不同意的. 可是对于下面代码.就有非常多人绕了: const int *p1; //p1能变.*p1不能变 int cons ...
- jquery-4 完整表单验证实例
jquery-4 完整表单验证实例 一.总结 一句话总结:在form的jquery对象中返回false即可终止表单提交. 1.验证的显示错误消息如何布局? 开始时隐藏,出现错误后显示 10 .erro ...
- DWG 对象与ArcGIS 要素的强制对应关系
转自原文DWG 对象与ArcGIS 要素的强制对应关系 DWG 对象与ArcGIS 要素的强制对应关系如下: Feature type DWG object types Point Point, ...
- Mysql存储过程中使用cursor
一.表 学生表 CREATE TABLE `t_student` ( `stuNum` int(11) NOT NULL auto_increment, `stuName` varchar ...
- C 语言常见 API(fprintf、fputs、fprintf)
1. fprintf:输出到文件描述符对应的文件 stderr:错误输出也是一种特殊的文件描述符 #define FatalError(str) fprintf(stderr, "%s\n& ...
- [Django] Start a new django project
Assume we already have a env created call 'demo-env': cd demo-env . bin/activate pip install django ...
- html5中input的type类型有哪些(总结)
html5中input的type类型有哪些(总结) 一.总结 一句话总结:时间.颜色.(邮件.电话.url).(数字.数字范围).搜索search 二.html5中input的type类型 值 描述 ...
- 通过手机其他iOS应用打开此文件
根据所处理文档的格式,提供本地设备(InApp)能处理该格式文档的所有应用(App).比如,demo中所处理的是pdf格式的文档,那么可以打开该文档的本地app有邮件.打印等等.仅支持ARC. dem ...
- BZOJ 1509 逃学的小孩 - 树型dp
传送门 题目大意: 在一棵树中, 每条边都有一个长度值, 现要求在树中选择 3 个点 X.Y. Z , 满足 X 到 Y 的距离不大于 X 到 Z 的距离, 且 X 到 Y 的距离与 Y 到 Z 的距 ...