2012-03-08 218 views
6

我需要开发一个应用程序的Windows Phone 7. 由于显而易见的原因,我必须验证我的表单。表单验证

我通常在WPF中编程,并使用ValidationRule的原则。但我无法在windows phone 7中找到相同的原理。

因此我的问题是,如何创建表单验证。

+0

我会宣传我的验证实施:http://vortexwolf.wordpress.com/2012/03/10/windows-phone-7-validation。我认为比互联网上的其他实现更容易使用。 – vorrtex 2012-03-09 22:50:41

回答

4

Windows Phone不支持开箱即用的表单验证。

这是一个blog post,它描述了如何滚动自定义控件来实现验证规则。

我将在我自己的应用程序中处理这个问题的方法是将验证逻辑放入我的模型类中,并在该模型上创建一个IsValid属性。模型类也会有一个Error属性,并带有描述验证问题的错误消息。我的UI层会调用myModel.IsValid,并在出现错误时显示错误消息。

+0

thx,我希望微软已经实施了一种方法 – David 2012-03-08 14:39:14

0

我复制了与在桌面上使用Silverlight相同的方法:INotifyDataErrorInfo接口。

Here我对它进行了更具体的描述,here可以下载示例项目的源代码。

的simpliest例子看起来如此:

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"); 
     } 
    } 
} 

它依赖于大量的补充类,但同时你自己写的代码很少。