I have a textbox in xaml here is code in .cs file:
public static readonly DependencyProperty dp =
DependencyProperty.Register(
"result", typeof( uint ), typeof( ui ),
new FrameworkPropertyMetadata( ( uint )100, new PropertyChangedCallback( ResultChanged ) ) );
private static void ResultChanged(
DependencyObject d, DependencyPropertyChangedEventArgs e )
{
var input = ( ui )d;
var value = ( uint )e.NewValue;
}
Above code works great it is not allowing any alphabets or invalid characters to be entered in the textbox. But how can i change above code so that user will not be able to enter “0” in the textbox? So basically allow all uint except 0.
There are many ways to do this….the simplest and easiest is just to use the NumericUpDown control from the Extended WPF Toolkit….set the min/max range and you are sorted.
http://wpftoolkit.codeplex.com/wikipage?title=NumericUpDown
If you do want to do the logic all yourself then….
You could specify a “Coercion Callback” and/or a “Validate Callback” in the Register of the Dependency Property depending on your needs/requirements i.e. do you need to fix the value to a range, or show an error indicator to the user?
“Coercion” is where you adjust the value to something else e.g. in this case you might decide to adjust any value of 0, to 1 (or possibly null).
“Validation” is where the value is checked and you say if it is correct or not (by returning true of false)…if you return false…then an exception gets raised.
You use ValidatesOnException on a Binding to the DependencyProperty in order for that “error” to be propagated to the user interface in the way of display of an ErrorTemplate (the default one shows a red border around a control).
http://www.shujaat.net/2010/07/wpf-validation-validatevaluecallback.html
http://msdn.microsoft.com/en-us/library/ms745795.aspx
http://wpf.2000things.com/2010/11/11/122-validating-a-dependency-property/
http://wpf.2000things.com/2010/11/12/123-coercing-a-dependency-property/
http://wpf.2000things.com/2010/12/09/150-an-example-of-using-propertychanged-and-coercevalue-callbacks/
In this case I will show just using the Coercion Callback…as I’m presuming you don’t want an invalid value to be waiting inside your TextBox. If you want the Validate one…then see the links above. (you don’t need a Changed callback, so that’s set to null).
There are also different techniques you can use like ValidationRules, possibly MaskedTextBox, and using PreviewTextInput.
http://social.msdn.microsoft.com/Forums/en/wpf/thread/990c635a-c14e-4614-b7e6-65471b0e0e26
How do I get a TextBox to only accept numeric input in WPF?
http://weblogs.asp.net/monikadyrda/archive/2009/06/24/wpf-textbox-validation.aspx