Tôi đã sao chép cùng một phương pháp mà tôi đã sử dụng với Silverlight trên máy tính để bàn: giao diện INotifyDataErrorInfo.
Here Tôi đã mô tả cụ thể hơn và here bạn có thể tải xuống mã nguồn của dự án mẫu.
Ví dụ đơn giản nhất trông như vậy:
View.xaml
<TextBox Text="{Binding SomeProperty, Mode=TwoWay, ValidatesOnNotifyDataErrors=True, NotifyOnValidationError=True}"
Style="{StaticResource ValidationTextBoxStyle}" />
View.xaml.cs
public MainPage()
{
InitializeComponent();
this.BindingValidationError += MainPage_BindingValidationError;
}
private void MainPage_BindingValidationError(object sender, ValidationErrorEventArgs e)
{
var state = e.Action == ValidationErrorEventAction.Added ? "Invalid" : "Valid";
VisualStateManager.GoToState((Control)e.OriginalSource, state, false);
}
ViewModel.cs
public class MainViewModel : ValidationViewModel
{
public MainViewModel()
{
this.Validator.AddValidationFor(() => this.SomeProperty).NotEmpty().Show("Enter a value");
}
private string someProperty;
public string SomeProperty
{
get { return someProperty; }
set
{
someProperty = value;
RaisePropertyChanged("SomeProperty");
}
}
}
Nó dựa trên rất nhiều lớp bổ sung, nhưng đồng thời có rất ít mã mà bạn sẽ tự viết.
Tôi sẽ quảng cáo việc triển khai xác thực của mình: http://vortexwolf.wordpress.com/2012/03/10/windows-phone-7-validation. Tôi nghĩ rằng nó dễ sử dụng hơn so với các triển khai khác trên internet. – vorrtex