轉帖|其它|編輯:郝浩|2011-03-31 13:57:12.000|閱讀 1729 次
概述:在我們綁定完數據后,在用戶輸入數據后,還需要進行用戶輸入合法性驗證,比如需要判斷 必填項,email地址輸入格式,日期格式是否正確等。wpf為我們提供了一種驗證用戶合法行的方式。依賴于綁定。在將實體數據綁定到視圖后,如果用戶輸入的視圖改變,則同時通知實體的屬性值改變。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
在我們綁定完數據后,在用戶輸入數據后,還需要進行用戶輸入合法性驗證,比如需要判斷 必填項,email地址輸入格式,日期格式是否正確等。
wpf為我們提供了一種驗證用戶合法行的方式。依賴于綁定。在將實體數據綁定到視圖后,如果用戶輸入的視圖改變,則同時通知實體的屬性值改變。先看代碼:
1. 構建一個要綁定到界面的實體。該實體實現了IDataErrorInfo接口,在接口里寫了驗證規則。
//實體 實現 IDataErrorInfo接口,并在 this[]索引器里定制自己的驗證規則
using System.ComponentModel;
namespace TextVerify
{
partial class eva:IDataErrorInfo
{
string _err;
public string Error
{
get { return _err; }
}
//定制驗證規則
public string this[string columnName]
{
get
{
string err = "";
switch (columnName)
{
case "Name":
if (string.IsNullOrEmpty(this.Name))
{
err = "名稱不能為空";
}
else
{
if (this.Name.Length > 8)
{
err = "名稱太長了,不能大于8個字符";
}
}
break;
case "Value":
if (this.value < 0 || this.value > 200)
{
err = "數字不合法";
}
break;
}
_err = err;
return _err;
}
}
}
}
2.頁面:
<Window x:Class="TextVerify.MainWindow"
xmlns="//schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x= "//schemas.microsoft.com/winfx/2006/xaml"
Title= "MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Name="eee">
<TextBox Height="23" HorizontalAlignment="Left"
Margin="152,73,0,0" Name="name"
Text="{Binding Path=Name, Mode=TwoWay,UpdateSourceTrigger=
'PropertyChanged',ValidatesOnDataErrors=True}"
VerticalAlignment= "Top" Width="120" >
<Validation.ErrorTemplate>
<ControlTemplate>
<!-- ControlTemplate要求只能有一個子級,所以加個容器控件DockPanel -->
<DockPanel>
<!-- AdornedElementPlaceholder就是要驗證的控件本身,本例里是個TextBox -->
<AdornedElementPlaceholder />
<TextBlock Foreground="Red" FontSize="20" Text="*" />
</DockPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
<Button Content="保 存" Height="23"
HorizontalAlignment="Left" Margin="152,114,0,0"
Name="button1"
VerticalAlignment= "Top" Width="75" Click="button1_Click" />
</Grid>
</Window>
32
頁面的后臺代碼:
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.Navigation;
using System.Windows.Shapes;
namespace TextVerify
{
/// <summary>
/// MainWindow.xaml 的交互邏輯
/// </summary>
public partial class MainWindow : Window
{
// EvaDAO ed = new EvaDAO();
// eva er = new eva();
public MainWindow(){}
//public MainWindow(eva er)
//{
// InitializeComponent();
// //eee.DataContext = er;
//}
/// <summary>
/// 保存
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button1_Click(object sender, RoutedEventArgs e)
{
//if(name.Text== "" || name.Text==""){
// return;
//}
//er.Name = name.Text;
//er.value = 222222;
////MessageBox.Show(er+ "===");
//ed.Save(er);
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
eee.DataContext = GetEvaFromDatabase();
}
private eva GetEvaFromDatabase()
{
//從數據庫獲得數據對象 <演示>
return new eva() { Name = "sa", value = 123 };
}
}
}
按F5運行后,嘗試輸入寫不合法數據??梢钥吹絋extbox的邊框變成紅色。這是一種默認的提示錯誤的風格方式,我們還可以對這個提示風格進行自定義。
注意Binding的下面兩個屬性:
ValidatesOnDataErrors 獲取或設置一個值,該值指示是否包含 DataErrorValidationRule。
ValidationRules 獲取用于檢查用戶輸入有效性的規則集合。
也就是說當我們設置了 Binding的ValidatesOnDataErrors="True" 時。WPF框架在構造Binding對象時,會自動的添加一個默認的DataErrorValidationRule到ValidationRules 屬性值(驗證規則列表)內。或者我們直接在ValidationRules 里添加我們需要的規則,比如下面是添加了兩個規則:
<Binding.ValidationRules>
<DataErrorValidationRule />
<ExceptionValidationRule></ExceptionValidationRule>
</Binding.ValidationRules>
這樣的寫法很有意思,貌似IOC的方式配置文件,比如spring.Net的配置文件,這樣的聲明ValidationRules的包含的規則。當WPF框架創建對象時自動的完成規則操作,并判斷ValidationRules內的規則數量,如果多于0個,就遍歷所有的規則集合,如果集合中包含了DataErrorValidationRule 并且實體類顯示了IDataErrorInfo
接口,就調用 實體內包含的 驗證規則。
ExceptionValidationRule 類是一個內置的規則,它檢查在綁定源屬性更新過程中引發的異常。這里驗證了Age的用戶輸入不可為空,當為空時,轉型成int(Age是int類型)時就會出錯。
通過創建一個從 ValidationRule 派生的類,可以創建自定義規則。下面我嘗試自定義驗證規則。
MSDN里對ValidateionRule的描述如下:
在使用 WPF 數據綁定模型時,可將 ValidationRules 與綁定對象關聯。若要創建自定義規則,請創建此類的子類并實現 Validate 方法。也可選擇使用內置的 ExceptionValidationRule(該類捕獲在源更新期間引發的異常)或 DataErrorValidationRule(該類檢查源對象的 IDataErrorInfo 實現所引發的錯誤)。
綁定引擎在每次將輸入值(即綁定目標屬性值)傳給綁定源屬性時將檢查與綁定關聯的每一個 ValidationRule。
頁面xaml代碼如下,而后置代碼不變。
下面我們看看如何更改在驗證失敗時的提示風格
<Window x:Class="TextVerify.MainWindow"
xmlns="//schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x= "//schemas.microsoft.com/winfx/2006/xaml"
Title= "MainWindow" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Name="eee">
<TextBox Height="23" HorizontalAlignment="Left"
Margin="152,73,0,0" Name="name"
Text="{Binding Path=Name, Mode=TwoWay,UpdateSourceTrigger=
'PropertyChanged',ValidatesOnDataErrors=True}"
VerticalAlignment= "Top" Width="120" >
<Validation.ErrorTemplate>
<ControlTemplate>
<!-- ControlTemplate要求只能有一個子級,所以加個容器控件DockPanel -->
<DockPanel>
<!-- AdornedElementPlaceholder就是要驗證的控件本身,本例里是個TextBox -->
<AdornedElementPlaceholder />
<TextBlock Foreground="Red" FontSize="20" Text="*" />
</DockPanel>
</ControlTemplate>
</Validation.ErrorTemplate>
</TextBox>
<Button Content="保 存" Height="23" HorizontalAlignment="Left" Margin="152,114,0,0"
Name= "button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
</Grid>
<Window.Resources>
<Style TargetType="TextBox">
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="Background" Value="#DDD" />
<Setter Property="Foreground" Value="Red" />
<Setter Property="ToolTip"
Value= "{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
</Style>
</Window.Resources>
</Window>
我們注意到Textbox.Validation屬性的ErrorTemplate是發生錯誤時使用的模板,我們重新new了一個ControlTemplate來代替這個模板。在這個模板里我們定義了一個DockPanel作為容器控件,使用 占位標記AdornedElementPlaceholder 標記了TextBox的位置,并在它后面添加兩個 字符"*"號。這可能有點難以理解。換個說法是,每個TextBox都有個Validation屬性,Validation包含了一些和驗證相關的像,包含有個當驗證失敗時的顯示模板。而我們重新定義了個顯示模板。這個模板里有個占位符,占位符表示TextBox本身,我們在這個模板的占位符后面添加一些字符 紅色的"*" 號。那么當TextBox在執行時,如果失敗,就會把 錯誤模板 顯示出來,并在 占位符位置 顯示自己。
我們換個另外的方式來改變視圖效果,使用style 方式。
在窗體資源里添加一個style,style這個東西呢,類似web開發中的css。他有個屬性TargetType 指示了這個樣式的作用域。本例中指示了 所有的TextBox,style的強大之處還有個Triggers就是觸發器。本例中觸發器指向一個屬性Validation.HasError屬性,當這屬性的值為"True"時,觸發Trigger包含的樣式。當不等于"True"時,自動改回原來的樣式。很強大吧。Setter元素提供了設置目標對象屬性的方法,我們直接更改了Textbox.ToolTop屬性,那么當鼠標移動到控件上時,就會顯示發生錯誤的原因。
1<Window.Resources>
2 <Style TargetType="TextBox">
3 <Style.Triggers>
4 <Trigger Property="Validation.HasError" Value="True">
5 <Setter Property="Background" Value="#DDD" />
6 <Setter Property="Foreground" Value="Red" />
7 <Setter Property="ToolTip"
8 Value= "{Binding RelativeSource={RelativeSource Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
9 </Trigger>
10 </Style.Triggers>
11 </Style>
12 </Window.Resources>
這句
<Setter Property="ToolTip"
Value="{Binding RelativeSource={RelativeSource Self},Path=(Validation.Errors)[0].ErrorContent}"/>
完成了獲得關聯數據源,并綁定錯誤提示的操作。
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn
文章轉載自:網易博客