Simple textbox validation wp7
Since wp7 is based on Silverlight 3 then input validation can be done (love or loathe it) via exceptions. Here’s a simple example…
<Grid x:Name="ContentPanel" Grid.Row="1"> <Border x:Name="errorBorder" Background="Red" Opacity="0"></Border> <TextBox Margin="8" Text="{Binding MyText, Mode=TwoWay, NotifyOnValidationError=True, ValidatesOnExceptions=True}" BindingValidationError="ContentPanel_BindingValidationError"> <TextBox.InputScope> <InputScope> <InputScope.Names> <InputScopeName>Default</InputScopeName> </InputScope.Names> </InputScope> </TextBox.InputScope> </TextBox> </Grid>
Note that the Textbox is bound to a text property and NotifyOnValidationError and ValidatesOnExceptions properties have been set to true. Also, the binding will be triggered when the TextBox loses focus. Setting NotifyOnValdationError means that my event handler for BindingValidationError event will be called when a validation error is detected. Following from that, a validation error will be detected when my bound property setter (for ‘MyText’) throws an exception. Here’s the code for that….
public partial class MainPage : PhoneApplicationPage, INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; public void OnPropertyChanged(string propertyName) { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } private string _myText; public string MyText { get { return _myText; } set { if (_myText != value) { if (value.Contains(".")) { throw new Exception("Cannot contain '.'"); } _myText = value; OnPropertyChanged("MyText"); } } } // Constructor public MainPage() { InitializeComponent(); DataContext = this; } private void ContentPanel_BindingValidationError(object sender, ValidationErrorEventArgs e) { errorBorder.Opacity = e.Action == ValidationErrorEventAction.Removed ? 0 : 100; } }
I haven’t been very creative with the visuals here…
Note that I have placed all of this code in the code-behind purely for convenience – I would usually implement this with a view model.
Comments