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);
            }
        }
    }
}
时间: 2024-08-24 13:31:21

D22_08_DataGrid编辑的相关文章

RDVECore来自锐动的无UI,高度抽象化API的视频编辑SDK--IOS版

1 编写目的 预期读者: 有视频编辑开发经验或者无经验的,打算或者正在使用"锐动IOS版RDVECore"的相关工程师. iOS软件工程师. 产品经理. QA 2 名词解释 分辨率:用于计算机视频处理的图像,以水平和垂直方向上所能显示的像素数来表示分辨率.常见视频分辨率的有1080P即1920x1080,720P即1080x720,640x480等. 帧率:每秒的帧数(fps)或者说帧率表示图形处理器处理场时每秒钟能够更新的次数. 码率: 数据传输时单位时间传送的数据位数,一般我们用的

5.5 进入编辑模式 5.6 vim命令模式 5.7 vim实践

5.5 进入编辑模式 5.6 vim命令模式 5.7 vim实践 扩展 vim的特殊用法 http://www.apelearn.com/bbs/thread-9334-1-1.html vim常用快捷键总结 http://www.apelearn.com/bbs/thread-407-1-1.html vim快速删除一段字符 http://www.apelearn.com/bbs/thread-842-1-1.html vim乱码 http://www.apelearn.com/bbs/thr

Android EditText+ListPopupWindow实现可编辑的下拉列表

使用场景 AutoCompleteEditText只有开始输入并且与输入的字符有匹配的时候才弹出下拉列表.Spinner的缺点是不可以编辑.所以本文介绍如何使用EditText+ListPopupWindow实现可编辑的下拉列表.使用场景可以是有记住密码功能的登录框. 给EditText增加上下箭头 我们需要一个箭头图片,放在EditText的右面,用来点击后弹出下拉列表.如图所示 要想实现这个很容易,只需要在布局文件中给EditText设置一个drawableRight的属性. <EditTe

Dynamics 365 for CRM: Sitemap站点图的可视化编辑功能

Dynamics 365 for CRM 提供了Sitemap站点图的可视化编辑功能 在之前的所有版本中,我们只能通过从系统中导出站点图的XML进行编辑后再导入(容易出错),或使用第三方的Sitemap编辑工具进行编辑(非常方便). 在Dynamics 365 for CRM 中原生地提供了站点图的可视化编辑功能,非常强大方便: 1.在默认解决方案或自定义解决方案的"客户端扩展"中,找到"站点地图"记录:如果没有则需要点击"添加现成",添加&qu

JQuery实现可直接编辑的表格

本文实例讲述了JQuery实现可直接编辑的表格.分享给大家供大家参考.具体分析如下: 功能: 创建一个表格,用户单击某个单元格后,可以直接修改单元格文本.在编辑状态下,用户可按回车键确认修改,按ESC键撤销修改. 效果如下图: 思路: 当用户点击某个单元格后,立即向该单元格内插入一个文本框,将它的宽.高都设置成与单元格相的数值.用户确认输入后,清空该单元格内的所有HTML代码,然后把内容设置为用户刚刚输入的文本. HTML代码: <table align="center">

数据库操作:编辑表向线上表更新

需求:表edit需要将数据更新到表release,里边会涉及增删改操作,如何做比较好??? 1.edit表是最新的数据,release表是线上表. 2.会有不同的容器调用release表,也就是需要解决容器之间的锁的问题,其他容器只有读操作,正在操控的容器有读写操作,因为更新操作无法做到原子,所以在操作之间可能会遇到其他容器查询为空或读了一半等出错的状态 a.   在另外一张表version里,打上到底使用哪张表.   即读取数据的时候是在两个表之间来回跳跃的 以下操作在我们做update的容器

用户编辑新建_AngularJS实现

实现思路:分步骤完成开发,逐渐添加功能:1.实现输出users对象.2.实现点击“编辑”按钮,在表单中显示firstname和lastname,并不可修改.3.实现“新建用户”和“编辑用户”的切换.4.实现“创建新用户”按钮. 1 <!doctype html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>无标题文档</title> 6 <scrip

线性布局中按钮在编辑框右边的布局方法

<LinearLayout android:id="@+id/pop_footprint_comment" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true&quo

UI_10 表视图的编辑、UITableViewController

读取plist文件并将其内容显示到表视图上.并添加编辑(增加,删除).移动cell的操作. plist文件内容如下: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" " http://www.apple.com/DTDs/PropertyList-1.0.dtd ">