IDataErrorInfo介面實作範例
利用IDataErrorInfo可以在介面上輸入錯誤時,告知使用者輸入的值是錯的。
基本上是 View-Model 要實作 IDataErrorInfo,XAML上要撰寫 Validation.ErrorTemplate,
再加上 Validation.HasError 要觸發 Trigger 修改 ToolTip。
程式碼如下:
<Window x:Class="IDataErrorInfo介面範例.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:IDataErrorInfo介面範例"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<local:VM/>
</Window.DataContext>
<Window.Resources>
<Style TargetType="{x:Type TextBox}">
<Style.Triggers>
<!--Trigger to Set the tooltip to inform abort the error.-->
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self},
Path=(Validation.Errors)[0].ErrorContent}"/>
</Trigger>
</Style.Triggers>
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<AdornedElementPlaceholder>
<Border BorderBrush="Red" BorderThickness="2"/>
</AdornedElementPlaceholder>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid>
<TextBox HorizontalAlignment="Left" Height="45" Margin="38,70,0,0"
TextWrapping="Wrap"
Text="{Binding MyValue,UpdateSourceTrigger=PropertyChanged,ValidatesOnDataErrors=True}"
VerticalAlignment="Top" Width="313"/>
<Label Content="猜猜我的英文名字?" HorizontalAlignment="Left" Height="24" Margin="38,41,0,0" VerticalAlignment="Top" Width="304"/>
<Label Margin="10,268,10,10" Content="{Binding Error}" Foreground="Red"/>
</Grid>
</Window>
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
namespace IDataErrorInfo介面範例
{
public class VM:INotifyPropertyChanged, IDataErrorInfo
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged(string PropertyName)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));
}
private string _MyValue;
public string MyValue
{
get { return _MyValue; }
set {
_MyValue = value;
OnPropertyChanged("MyValue");
}
}
private string _ValidationErrorMsg;
//給 view 顯示目前的錯誤訊息
public string Error
{
get { return _ValidationErrorMsg; }
set
{
_ValidationErrorMsg = value;
OnPropertyChanged("Error");
}
}
public string this[string columnName]
{
get
{
string errmsg = "";
if (columnName == "MyValue")
{
int i = string.Compare(this.MyValue, "Alvin");
if (i == 0)
{
errmsg = "";
}
else
{
errmsg = "這不是我的名字!";
}
}
this.Error = errmsg;
return errmsg;
}
}
}
}