Answered by:

TextBox input validation

Question

How can I validate input for my textboxes? For example I have an application where I want to input several numbers in the textboxes. The primary validation constraint is that I want the user to be able to input only valid real numbers. Some of the textboxes should contain only positive real numbers. Also I want to be able to do comparisons between the different values (for example I have a minimum speed textbox, and maximum speed textbox, so there's one more rule here: min <= max). Also, if the user is currently editing a textbox, he should be able to cancel the modifications, by pressing escape. How can I do all these with Avalon/WPF?

1. I have a 'motor' private field of type 'Motor' in the code behind file. I want to bind to its 'Resolution' property (Motor.Resolution). How do I do this? I've tried setting a static resource like: <l:Motor x:Name="motor" x:Key="motorkey" /> and then use the key in the XAML file. But it doesn't work, it's like it has two Motor objects (the private field, and the static resource). How can I bind to it (the private field)?

2. I have two textboxes, for MinSpeed and MaxSpeed. Logically, MinSpeed should not be greater than MaxSpeed. How does the validation rule mechanism come in handy here?

Yes <c:DoubleRangeRule Min="0.0" Max="90.0"/> works fine, but then the values are hardcoded, I thought you wanted them to be dynamic.I was thinking something in the line of: <local:ValidateMin Motor="Motor">. But I can't get it to work.

Up to this point, we've used another control as the source for all of our binding examples. In most XAML-based projects, however, you will be binding to sources other than other controls. The key to most data binding is the Source property. In the previous examples, we are using the ElementName property, which is used to bind to a control, instead of using the Source property. For most applications, you will want to bind to more significant sources, such as XML or .NET objects. XAML supports this with its data provider objects. There are two types of data providers built into XAML: ObjectDataProvider and XmlDataProvider. The ObjectDataProvider is used for binding to and from .NET objects, and, not surprisingly, the XmlDataProvider is used to bind to and from XML fragments and documents. You can specify a data provider in the resources section of any XAML container."