Validation of UI input parameters in WPF is a frequently requirement. There are several approaches to realize an input validation. You can use custom ValidationRule, ExceptionValidationRule or IDataErrorInfo. Excellent descriptions how to use validation in WPF can be found here:
- http://blogs.msdn.com/b/wpfsdk/archive/2007/10/02/data-validation-in-3-5.aspx
- http://www.codeproject.com/Articles/15239/Validation-in-Windows-Presentation-Foundation
<Style x:Key="textBoxInError" TargetType="{x:Type TextBox}"> <Style.Triggers> <Trigger Property="Validation.HasError" Value="true"> <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}" /> </Trigger> </Style.Triggers> </Style>This works fine, but produces some exceptions in the Output window, if the error is corrected after occurring:
System.Windows.Data Error: 17 :
Cannot get 'Item[]' value (type 'ValidationError') from '(Validation.Errors)'
(type 'ReadOnlyObservableCollection`1').
BindingExpression:Path=(0)[0].ErrorContent; DataItem='TextBox'
(Name='Input1'); target element is 'TextBox'
(Name='Input1'); target property is 'ToolTip' (type 'Object')
ArgumentOutOfRangeException:'System.ArgumentOutOfRangeException: Specified
argument was out of the range of valid values.
Parameter name: index'
<Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors).CurrentItem.ErrorContent}"/>