<Window x:Class="DataBindingExam.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        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>
                        <DataErrorValidationRule></DataErrorValidationRule>
                    </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();
            }
        }
    }

}

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ClassLibrary
{
    public class Product:IDataErrorInfo
    {
        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;
        }

        public string Error
        {
            get { return null; }
        }

        public string this[string columnName]
        {
            get
            {
                bool valid = true;
                if (columnName=="UnitCost")
                {
                    if (UnitCost<0)
                    {
                        valid = false;
                    }
                }
                if (!valid)
                {
                    return "UnitCost can not be negative";
                }
                else
                {
                    return null;
                }
                
            }
        }
    }
}

WPF IDataErrorInfo使用-数据对象上验证的更多相关文章

  1. WPF中的数据验证

    数据验证 WPF的Binding使得数据能够在数据源和目标之间流通,在数据流通的中间,便能够对数据做一些处理. 数据转换和数据验证便是在数据从源到目标 or 从目标到源 的时候对数据的验证和转换. V ...

  2. WPF使用IDataErrorInfo进行数据校验

    这篇博客将介绍如何使用IDataErrorInfo进行数据校验.下面直接看例子.一个Customer类,两个属性(FirstName, Age) class Customer { public str ...

  3. MVC中的数据注解和验证

    数据注解和验证 用户输入验证在客户端浏览器中需要执行验证逻辑. 在客户端也需要执行. 注解是一种通用机制, 可以用来向框架注入元数据, 同时, 框架不只驱动元数据的验证, 还可以在生成显示和编辑模型的 ...

  4. 数据注解和验证 – ASP.NET MVC 4 系列

           不仅在客户端浏览器中需要执行验证逻辑,在服务器端也需要执行.客户端验证能即时给出一个错误反馈(阻止请求发送至服务器),是时下 Web 应用程序所期望的特性.服务器端验证,主要是因为来自网 ...

  5. WPF的ComboBox 数据模板自定义

    WPF的ComboBox 有些时候不能满足用户需求,需要对数据内容和样式进行自定义,下面就简要介绍一下用数据模板(DataTemplate)的方式对ComboBox 内容进行定制: 原型设计如下: 步 ...

  6. WPF中的数据模板(DataTemplate)(转)

    原文地址 http://www.cnblogs.com/zhouyinhui/archive/2007/03/30/694388.html WPF中的数据模板(DataTemplate)        ...

  7. ASP.NET MVC5(四):数据注解和验证

    前言 用户输入验证的工作,不仅要在客户端浏览器中执行,还要在服务端执行.主要原因是客户端验证会对输入数据给出即时反馈,提高用户体验:服务器端验证,主要是因为不能完全信任用户提供的数据.ASP.NET ...

  8. ASP.NET MVC5高级编程 之 数据注解和验证

    客户端验证逻辑会对用户向表单输入的数据给出一个即时反馈.而之所以需要服务器端验证,是因为来自网络的信息都是不能被信任的. 当在ASP.NET MVC设计模式上下文中谈论验证时,主要关注的是验证模型的值 ...

  9. XML的应用 ---- 从一个范例看xml数据、xsd验证、xslt样式

    从一个范例看XML的应用 引言 如果你已经看了Asp.Net Ajax的两种基本开发模式 这篇文章,你可能很快会发现这样一个问题:在那篇文章的方式2中,客户端仅仅是发送了页面上一个文本框的内容到服务端 ...

随机推荐

  1. IHookHelper的用法

    1.实例化IHookHelper 对象: IHookHelper m_hookHelper = new HookHelperClass();  m_hookHelper.Hook = this.axM ...

  2. python 设计模式之 单例模式

    单例模式是做为"全局变量"的替代品出现的.所以它具有全局变量的特点:全局可见.贯穿应用程序的整个生命期,保证在程序执行中,某个类仅仅存在一个实例,所以通常不希望类中的构造函数被调用 ...

  3. Qt5.4.2编译 qtpropertybrowser-2.51(从4修改到5的除错过程)

    qtpropertybrowser是一个洛基亚时代的一个产物,其实它就是QtDesigner侧栏那种样子而已.网上大部分的都只适用于Qt4,今天头脑发热想用Qt5编译一下,发觉一大堆错误,因为Qt4有 ...

  4. php课程 6-24 字符串函数有哪些(复习)

    php课程 6-24 字符串函数有哪些(复习) 一.总结 一句话总结: 二.php课程 6-24 字符串函数有哪些(复习) 上次复习:--------------------------------- ...

  5. 我的Java开发学习之旅------&gt;Java经典排序算法之归并排序

    一.归并排序 归并排序是建立在归并操作上的一种有效的排序算法,该算法是採用分治法(Divide and Conquer)的一个很典型的应用.将已有序的子序列合并,得到全然有序的序列.即先使每一个子序列 ...

  6. EL表达式JSON应用

    由于之前在学校写的jsp页面都是夹杂着java代码的,所以之前写了个jsp,满满的<%%>和java代码,老师说那样太不美观了啊!!!要全部用EL表达式替代了.本人还是太笨了,弄了一上午才 ...

  7. Mochiweb的设计分析

    http://blog.csdn.net/dp0304/article/details/6994435 Web服务器的基本工作大致分3步: 接收HTTP请求: 处理HTTP请求,生成响应内容: 发送响 ...

  8. 学习鸟哥的Linux私房菜笔记(6)——过滤器、输入输出及管道

    一.过滤器 Linux中的应用工具分为三种: 交互工具 过滤器 编辑器 能够接受数据,过滤再输出的工具,称之为过滤器 对过滤器和进程,存在着输入源与输出对象 二.输入.输出.重定向 输入:过滤器的数据 ...

  9. Java Math数字处理类与包装类习题

    //创建Integer类对象,并以int型返回 Integer intAb = new Integer("123"); System.out.println(intAb.intVa ...

  10. 使用 jquery 的 上传文件插件 uploadify 3.1 配合 java 来做一个简单的文件上次功能。并且在界面上有radio 的选择内容也要上传

    使用 jquery 的 上传文件插件 uploadify 3.1 配合 java 来做一个简单的文件上次功能.并且在界面上有radio 的选择内容也要上传 uploadify 插件的 下载和文档地址  ...