<Window x:Class="DataBindingExam.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:DataBindingExam"
        Title="MainWindow" Height="344.636" Width="365.422">
    <Grid Name="grid">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"></RowDefinition>
            <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>
        <StackPanel Grid.Row="0" Grid.ColumnSpan="2" Grid.Column="0" Margin="3" Orientation="Horizontal" VerticalAlignment="Center">
            <TextBlock Margin="3">ID:</TextBlock>
            <TextBox Name="txtID" Margin="3" MinWidth="100"></TextBox>
            <Button Name="btnQuery" Margin="3" MinWidth="50" Click="btnQuery_Click_1">查询</Button>
            <Button Name="btnUpdate" Margin="3" MinWidth="50" Click="btnUpdate_Click_1">更新</Button>
            <Button Name="btnInsert" Margin="3" MinWidth="50" Click="btnInsert_Click_1">插入</Button>
            <Button Name="btnDelete" Margin="3" MinWidth="50" Click="btnDelete_Click_1">删除</Button>
        </StackPanel>
        <TextBlock Margin="3" Grid.Row="1" Grid.Column="0" VerticalAlignment="Center">CategoryID</TextBlock>
        <TextBox Name="txtCategoryID" Margin="3" Grid.Row="1" Grid.Column="1" VerticalAlignment="Center"
                 Text="{Binding Path=CategoryID}"></TextBox>
        
        <TextBlock Margin="3" Grid.Row="2" Grid.Column="0" VerticalAlignment="Center">ModelNumber</TextBlock>
        <TextBox Name="txtModelNumber" Margin="3" Grid.Row="2" Grid.Column="1" VerticalAlignment="Center"
                 Text="{Binding Path=ModelNumber}"></TextBox>

        <TextBlock Margin="3" Grid.Row="3" Grid.Column="0" VerticalAlignment="Center">ModelName</TextBlock>
        <TextBox Name="txtModelName" Margin="3" Grid.Row="3" Grid.Column="1" VerticalAlignment="Center"
                 Text="{Binding Path=ModelName}"></TextBox>

        <TextBlock Margin="3" Grid.Row="4" Grid.Column="0" VerticalAlignment="Center">ProductImage</TextBlock>
        <TextBox Name="txtProductImage" Margin="4" Grid.Row="4" Grid.Column="1" VerticalAlignment="Center"
                 Text="{Binding Path=ProductImage}"></TextBox>

        <TextBlock Margin="3" Grid.Row="5" Grid.Column="0" VerticalAlignment="Center">UnitCost</TextBlock>
        <TextBox Name="txtUnitCost" Margin="3" Grid.Row="5" Grid.Column="1" VerticalAlignment="Center"  Validation.Error="txtUnitCost_Error_1">
            <TextBox.Text>
                <Binding Path="UnitCost" NotifyOnValidationError="true">
                    <Binding.ValidationRules>
                        <local:PriceValidationRule Min="10" Max="100"></local:PriceValidationRule>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>

        <TextBox Name="txtDescription" Margin="4" Grid.Row="6" Grid.Column="0" Grid.ColumnSpan="2"
                 Text="{Binding Path=Description}" TextWrapping="Wrap"></TextBox>
    </Grid>

</Window>

using ClassLibrary;
using System;
using System.Collections.Generic;
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 DataBindingExam
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void btnQuery_Click_1(object sender, RoutedEventArgs e)
        {
            int id = Convert.ToInt32(txtID.Text);
            Product p = StoreDB.GetProductByID(id);
            grid.DataContext = p;
        }

        private void btnUpdate_Click_1(object sender, RoutedEventArgs e)
        {
            int categoryID=Convert.ToInt32(txtCategoryID.Text);
            decimal unitCost = Convert.ToDecimal(txtUnitCost.Text);

            Product p = new Product()
            {
                CategoryID = categoryID,
                ModelNumber = txtModelNumber.Text,
                ModelName = txtModelName.Text,
                ProductImage = txtProductImage.Text,
                UnitCost = unitCost,
                Description = txtDescription.Text
            };
            int productID = Convert.ToInt32(txtID.Text);
            StoreDB.UpdateProductByID(productID, p);
        }

        private void btnInsert_Click_1(object sender, RoutedEventArgs e)
        {
            int categoryID = Convert.ToInt32(txtCategoryID.Text);
            decimal unitCost = Convert.ToDecimal(txtUnitCost.Text);
            Product p = new Product()
            {
                CategoryID = categoryID,
                ModelNumber = txtModelNumber.Text,
                ModelName = txtModelName.Text,
                ProductImage = txtProductImage.Text,
                UnitCost = unitCost,
                Description = txtDescription.Text
            };
            StoreDB.InsertProduct(p);
        }

        private void btnDelete_Click_1(object sender, RoutedEventArgs e)
        {
            int productID = Convert.ToInt32(txtID.Text);
            StoreDB.DeleteProductByID(productID);
        }

        private void txtUnitCost_Error_1(object sender, ValidationErrorEventArgs e)
        {
            if (e.Action==ValidationErrorEventAction.Added)
            {
                MessageBox.Show(e.Error.ErrorContent.ToString());
            }
        }
    }
}

using System;
using System.Collections.Generic;
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();
            }
        }
    }

}

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 System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;

namespace DataBindingExam
{
    public class PriceValidationRule:ValidationRule
    {
        public decimal Max { get; set; }
        public decimal Min { get; set; }
        public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
        {
            decimal price = 0;
            if (decimal.TryParse(value.ToString(), out price))
            {
                if (price > Min && price<Max)
                {
                    return new ValidationResult(true, null);
                }
                else
                {
                    return new ValidationResult(false, "Illegal,price must between "+Min+"~"+Max);
                }
            }
            else
            {
                return new ValidationResult(false, "Can not convert to decimal");
            }
        }
    }
}

最新文章

  1. Java中堆的实现类PriorityQueue队列接口Queue
  2. log4j2配置
  3. 转-CSS3 圆角(border-radius)
  4. Flink DataSet API Programming Guide
  5. hdu 4638 树状数组
  6. Recommender Systems 基于知识的推荐
  7. 另一种root方法,Android boot.img破解
  8. Android eng版系统烧录
  9. vim: 字符串替换
  10. JSP标准标签库(JSTL)--JSTL简介与安装
  11. ThinkPHP中:用户登录权限验证类
  12. AspNet Core Web 应用程序的启动 当项目中 没有Startup.cs 类如何设置启动 配置等等
  13. css 两端对齐的多种实现方式
  14. 关于jquery插件模板的两个案例
  15. drool-6.5的自学demo
  16. springboot+mybatis+pagehelper
  17. Django中STATIC_URL、STATIC_ROOT、STATICFILES_DIRS 的区别关系
  18. erlang遍历目录
  19. python 模块之-configparser
  20. JS-事件对象(鼠标键盘事件)

热门文章

  1. windows 下安装git
  2. Redis使用文档一
  3. [React] Break up components into smaller pieces using Functional Components
  4. Linux 网络编程系列教程
  5. 曼德勃罗(Mandelbrot)集合与其编程实现
  6. BZOJ 1699 [Usaco2007 Jan]Balanced Lineup排队 线段树
  7. js如何实现动态克隆一个表格?
  8. log4erl Configuration
  9. Filter,Listener(转)
  10. [GeekBand] STL 仿函数入门详解