首页 > 代码库 > D22_08_DataGrid编辑
D22_08_DataGrid编辑
<Window x:Class="demo.DataGridEditing" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="DataGridEditing" Height="635" Width="517" xmlns:col="clr-namespace:System.Collections;assembly=mscorlib" xmlns:sys="clr-namespace:System;assembly=mscorlib" xmlns:local="clr-namespace:demo"> <Grid> <DataGrid x:Name="gridProducts" Margin="5" AutoGenerateColumns="False" > <DataGrid.Columns> <DataGridTextColumn Header="Product" Width="175" Binding="{Binding ModelName}"></DataGridTextColumn> <DataGridTextColumn Header="Price"> <DataGridTextColumn.Binding> <Binding Path="UnitCost" StringFormat="{}{0:C}"> <Binding.ValidationRules> <local:PositivePriceRule Max="999.99" /> </Binding.ValidationRules> </Binding> </DataGridTextColumn.Binding> </DataGridTextColumn> <DataGridTextColumn Header="Model Number" Binding="{Binding ModelNumber}"></DataGridTextColumn> <!--设置所属类别下拉框,categoryColumn绑定到ICollection<Category>--> <DataGridComboBoxColumn Header="Category" x:Name="categoryColumn" SelectedValueBinding="{Binding Path=CategoryID}" SelectedValuePath="CategoryID" DisplayMemberPath="CategoryName" ></DataGridComboBoxColumn> <!--设置日期列--> <DataGridTemplateColumn Header="Date Added"> <DataGridTemplateColumn.CellTemplate> <DataTemplate> <TextBlock Margin="4" VerticalAlignment="Center" Text="{Binding Path=DateAdded, StringFormat={}{0:d}}"></TextBlock> </DataTemplate> </DataGridTemplateColumn.CellTemplate> <DataGridTemplateColumn.CellEditingTemplate> <DataTemplate> <DatePicker Margin="4" SelectedDate="{Binding Path=DateAdded}"></DatePicker> </DataTemplate> </DataGridTemplateColumn.CellEditingTemplate> </DataGridTemplateColumn> </DataGrid.Columns> </DataGrid> </Grid></Window>
DataGridEditing(窗体类)
using System;using System.Collections.Generic;using System.Linq;using System.Text;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.Shapes;using StoreDatabase;namespace demo{ /// <summary> /// DataGridEditing.xaml 的交互逻辑 /// </summary> public partial class DataGridEditing : Window { public DataGridEditing() { InitializeComponent(); //ICollection<Category> categoryColumn.ItemsSource = App.StoreDb.GetCategories(); //ICollection<Product> gridProducts.ItemsSource = App.StoreDb.GetProducts(); } }}
StoreDB
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Data;using System.Data.SqlClient;using System.Collections.ObjectModel;namespace StoreDatabase{ public class StoreDB { private string connectionString = StoreDatabase.Properties.Settings.Default.Store; public ICollection<Product> GetProducts() { SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("GetProducts", con); cmd.CommandType = CommandType.StoredProcedure; ObservableCollection<Product> products = new ObservableCollection<Product>(); try { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { // Create a Product object that wraps the // current record. Product product = new Product((string)reader["ModelNumber"], (string)reader["ModelName"], (decimal)reader["UnitCost"], (string)reader["Description"], (int)reader["ProductID"], (string)reader["CategoryName"], (string)reader["ProductImage"]); // Add to collection products.Add(product); } } finally { con.Close(); } return products; } public ICollection<Category> GetCategoriesAndProducts() { SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("GetProducts", con); cmd.CommandType = CommandType.StoredProcedure; SqlDataAdapter adapter = new SqlDataAdapter(cmd); DataSet ds = new DataSet(); adapter.Fill(ds, "Products"); cmd.CommandText = "GetCategories"; adapter.Fill(ds, "Categories"); // Set up a relation between these tables (optional). DataRelation relCategoryProduct = new DataRelation("CategoryProduct", ds.Tables["Categories"].Columns["CategoryID"], ds.Tables["Products"].Columns["CategoryID"]); ds.Relations.Add(relCategoryProduct); ObservableCollection<Category> categories = new ObservableCollection<Category>(); foreach (DataRow categoryRow in ds.Tables["Categories"].Rows) { ObservableCollection<Product> products = new ObservableCollection<Product>(); foreach (DataRow productRow in categoryRow.GetChildRows(relCategoryProduct)) { products.Add(new Product(productRow["ModelNumber"].ToString(), productRow["ModelName"].ToString(), (decimal)productRow["UnitCost"], productRow["Description"].ToString())); } categories.Add(new Category(categoryRow["CategoryName"].ToString(), products)); } return categories; } public ICollection<Category> GetCategories() { SqlConnection con = new SqlConnection(connectionString); SqlCommand cmd = new SqlCommand("GetCategories", con); cmd.CommandType = CommandType.StoredProcedure; ObservableCollection<Category> categories = new ObservableCollection<Category>(); try { con.Open(); SqlDataReader reader = cmd.ExecuteReader(); while (reader.Read()) { // Create a Category object that wraps the // current record. Category category = new Category((string)reader["CategoryName"], (int)reader["CategoryID"]); // Add to collection categories.Add(category); } } finally { con.Close(); } return categories; } }}
Category
using System;using System.Collections.Generic;using System.Text;using System.Collections.ObjectModel;using System.ComponentModel;namespace StoreDatabase{ public class Category : INotifyPropertyChanged { private string categoryName; public string CategoryName { get { return categoryName; } set { categoryName = value; OnPropertyChanged(new PropertyChangedEventArgs("CategoryName")); } } // For DataGridComboBoxColumn example. private int categoryID; public int CategoryID { get { return categoryID; } set { categoryID = value; OnPropertyChanged(new PropertyChangedEventArgs("CategoryID")); } } private ObservableCollection<Product> products; public ObservableCollection<Product> Products { get { return products; } set { products = value; OnPropertyChanged(new PropertyChangedEventArgs("Products")); } } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) PropertyChanged(this, e); } public Category(string categoryName, ObservableCollection<Product> products) { CategoryName = categoryName; Products = products; } public Category(string categoryName, int categoryID) { CategoryName = categoryName; CategoryID = categoryID; } }}
Product
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.ComponentModel;namespace StoreDatabase{ public class Product : INotifyPropertyChanged { private string modelNumber; public string ModelNumber { get { return modelNumber; } set { modelNumber = value; OnPropertyChanged(new PropertyChangedEventArgs("ModelNumber")); } } private string modelName; public string ModelName { get { return modelName; } set { modelName = value; OnPropertyChanged(new PropertyChangedEventArgs("ModelName")); } } private decimal unitCost; public decimal UnitCost { get { return unitCost; } set { unitCost = value; OnPropertyChanged(new PropertyChangedEventArgs("UnitCost")); } } private string description; public string Description { get { return description; } set { description = value; OnPropertyChanged(new PropertyChangedEventArgs("Description")); } } private string categoryName; public string CategoryName { get { return categoryName; } set { categoryName = value; } } // For DataGridComboBoxColumn example. private int categoryID; public int CategoryID { get { return categoryID; } set { categoryID = value; } } private string productImagePath; public string ProductImagePath { get { return productImagePath; } set { productImagePath = value; } } public Product(string modelNumber, string modelName, decimal unitCost, string description) { ModelNumber = modelNumber; ModelName = modelName; UnitCost = unitCost; Description = description; } public Product(string modelNumber, string modelName, decimal unitCost, string description, string productImagePath) : this(modelNumber, modelName, unitCost, description) { ProductImagePath = productImagePath; } public Product(string modelNumber, string modelName, decimal unitCost, string description, int categoryID, string categoryName, string productImagePath) : this(modelNumber, modelName, unitCost, description) { CategoryName = categoryName; ProductImagePath = productImagePath; CategoryID = categoryID; } public override string ToString() { return ModelName + " (" + ModelNumber + ")"; } public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(PropertyChangedEventArgs e) { if (PropertyChanged != null) PropertyChanged(this, e); } // This for testing date editing. The value isn‘t actually stored in the database. private DateTime dateAdded = DateTime.Today; public DateTime DateAdded { get { return dateAdded; } set { dateAdded = value; } } }}
PositivePriceRule 规则校验类
using System;using System.Collections.Generic;using System.Text;using System.Windows.Controls;using System.Globalization;namespace demo{ public class PositivePriceRule : ValidationRule { private decimal min = 0; private decimal max = Decimal.MaxValue; public decimal Min { get { return min; } set { min = value; } } public decimal Max { get { return max; } set { max = value; } } public override ValidationResult Validate(object value, CultureInfo cultureInfo) { decimal price = 0; try { if (((string)value).Length > 0) // Allow number styles with currency symbols like $. price = Decimal.Parse((string)value, System.Globalization.NumberStyles.Any); } catch (Exception e) { return new ValidationResult(false, "Illegal characters."); } if ((price < Min) || (price > Max)) { return new ValidationResult(false, "Not in the range " + Min + " to " + Max + "."); } else { return new ValidationResult(true, null); } } }}
D22_08_DataGrid编辑
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。