WPF 自定义验证规则
<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");
}
}
}
}
WPF 自定义验证规则的更多相关文章
- yii2中自定义验证规则rules
作者:白狼 出处:www.manks.top/article/yii2_custom_rules 本文版权归作者,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追 ...
- easyui的validatebox重写自定义验证规则的几个实例
validatebox已经实现的几个规则: 验证规则是根据使用需求和验证类型属性来定义的,这些规则已经实现(easyui API): email:匹配E-Mail的正则表达式规则. url:匹配URL ...
- yii2中的rules 自定义验证规则详解
yii2的一个强大之处之一就是他的Form组件,既方便又安全.有些小伙伴感觉用yii一段时间了,好嘛,除了比tp"难懂"好像啥都没有. 领导安排搞一个注册的功能,这家伙刷刷刷的又是 ...
- thinkPHP5.0验证器自定义验证规则
自定义验证规则 protected $rule = [ 'views' => 'require|number|checkviews:0',//checkviews为自定义验证规则,0是传过去的规 ...
- Jquery Validate 相关参数及常用的自定义验证规则
一.官网地址:http://bassistance.de/jquery-plugins/jquery-plugin-validation 二.默认校验规则 1 2 3 4 5 6 7 8 9 10 1 ...
- validatebox自定义验证规则以及使用
//===============jsp======state==== //开启验证 <script type="text/javascript"> y ...
- Django【第16篇】:Django之Form组件自定义验证规则
自定义验证规则以及中间件简单介绍 1.python2和python3中的区别 对于python2内置的字符串类型有str和unicode 比如:"abc"是字符串,u"你 ...
- Jquery Validate自定义验证规则,一个汉字等于两个字符长度
使用Jquery validate时写的一些东西,在这里做个笔记 在使用 Jquery validate 的minlength和maxlength进行文本框内容长度验证的时候,对于一个汉字的长度检测结 ...
- 爱上MVC3~为下拉列表框添加一个自定义验证规则
回到目录 开发它的原因: 之前的同事,也是我的哥们,问我下拉列表框是否可以支持验证,这个问题看似简单,但确实MVC里有为我们提供,所以,只能自己写个扩展了,即自己写一个attribute特性,让它继承 ...
随机推荐
- Hibernate的ID主键生成策略
ID生成策略(一) 通过XML配置实现ID自己主动生成(測试uuid和native) 之前我们讲了除了通过注解的方式来创建一个持久化bean外.也能够在须要持久化的bean的包路径下创建一个与bean ...
- RSA算法原理(转)
如果你问我,哪一种算法最重要?我可能会回答“公钥加密算法”.因为它是计算机通信安全的基石,保证了加密数据不会被破解.你可以想象一下,信用卡交易被破解的后果. 进入正题之前,我先简单介绍一下,什么是”公 ...
- 七个帮助你处理Web页面层布局的jQuery插件
1.UI.Layout jQuery UI布局插件 官方网站:http://layout.jquery-dev.com/index.cfm 使用大小可折叠的嵌套面板和大量选项创建高级UI布局.布局可 ...
- 使用Toolbar + DrawerLayout快速实现高大上菜单侧滑
如果你有在关注一些遵循最新的Material Design设计规范的应用的话(如果没有,假设你有!),也许会发现有很多使用了看起来很舒服.很高大上的侧滑菜单动画效果,示例如下(via 参考2): 今天 ...
- C++生成GIF小结
声明:所有权利保留. 转载必须说明出处:http://blog.csdn.net/cartzhang/article/details/44020175 近来需要把BMP或Kinect的内存图片多张合成 ...
- 【codeforces 750C】New Year and Rating(做法2)
time limit per test2 seconds memory limit per test256 megabytes inputstandard input outputstandard o ...
- 使用JSONlib简单的转换json操作
在使用jsonlib操作之前 需要引入json及5个依赖包,依赖包版本不能最新,lang与collections有不兼容现象. 官方地址:http://json-lib.sourceforge.net ...
- Web开发的编码解决中文乱码
中文乱码有两个环节会出现 第一,从请求体中获得的数据 从请求体中获得的数据要为其进行编码,默认为ISO-8859-1,所以在使用getParameter()时先调用setCharacterEncodi ...
- (ubuntu 下)tensorflow 的安装及版本升级
对于 CPU 版本 pip3 install –upgrade tensorflow 对于 GPU 版本: pip3 install –upgrade tensorflow-gpu [TensorFl ...
- instsrv.exe用法
这个小工具是用以安装和卸载可执行的服务和指派服务名给这些可执行的服务的. 一:绑定程序和服务 这里我们设定要将F:\cpu.exe 以 abc 的名称显示作为服务的话,我们应当这样子做: 在开 ...