接著上一回的話題,繼續來研究資料批示特性,先拿簡單的RageAttribute來弄弄,接著上次的樣本,添加一個Age屬性,並加上RangeAttribute。
[Range(20,60,ErrorMessage="年齡範圍在20與60之間。")] [Display(Name="年齡",Description="歌手年齡。")] public int Age { get; set; }
接著把XAML也補完整。
<sdk:Label x:Name="lbAge" Target="{Binding ElementName=txtAge}" Grid.Column="0" Grid.Row="2" FontSize="14" Margin="1,1,20,1"/> <StackPanel Grid.Column="1" Grid.Row="2" Orientation="Horizontal"> <TextBox x:Name="txtAge" Margin="1,1" Width="165" Text="{Binding Age}"/> <sdk:DescriptionViewer Target="{Binding ElementName=txtAge}"/> </StackPanel>
是不是可以了呢? 運行一下,定義的範圍在20-60,現在輸入100,然後把焦點文字框移走,結果發現,沒有發生驗證。 好,簡單的不行,繼續探索,把屬性的定義改成這樣:
int m_Age = 20; [Range(20, 60, ErrorMessage = "年齡範圍在20與60之間。")] [Display(Name = "年齡", Description = "歌手年齡。")] public int Age { get { return this.m_Age; } set { Validator.ValidateProperty(value, new ValidationContext(this, null, null) { MemberName = "Age" }); this.m_Age = value; } }
然後再次運行,喲,上帝!還是不行,怎麼了?Validator的驗證方法也調用了,為什麼還不行呢?不要氣餒,繼續,還記得在XAML中寫的綁定擴充標記不?想起來了嗎? 1、預設是單向綁定Mode = Oneway; 2、沒有顯式設定啟用驗證。 嗯,這下明白了,再改改
<TextBox x:Name="txtAge" Margin="1,1" Width="165" Text="{Binding Age,Mode=TwoWay,ValidatesOnExceptions=true, NotifyOnValidationError=true}"/>
再運行,這回驗證了,但是,拋出了異常。那有沒有辦法不拋出異常而顯示友好的錯誤提示呢?答案當然有,使用ValidationSummary 。
<sdk:ValidationSummary Grid.Row="3" Grid.ColumnSpan="2"/>
再次按下F5,驗證失敗後仍然拋出異常,這時候,你可能有些失望。
山重水複疑無路,柳暗花明會成功,這時候,你在項目上右擊,選擇“在瀏覽器中查看”,啊,眼前一亮,出來了。
現在,總結一下方法:
1、在定義公用屬性時加上對應的特性,如RangeAttribute;
2、在屬性的set訪問器上調用Validator的ValidateProperty方法;
3、在XAML或前台綁定時,將Binding 的Mode設定為TwoWay,ValidatesOnExceptions和NotifyOnValidationError設定為True;
4、添加ValidationSummary控制項以顯示錯誤清單,當然,不加也可以,看看下面的。
5、在非debug模式下運行程式。