DaveDev
DaveDev

Reputation: 42175

How can I fire an event if a user enters too large a value in a TextBox?

At the moment I have a text box that is bound to a byte property. If the user enters between 0 and 255 the application behaves as expected and the property's setter executes.

However, if the user enters 256 or greater the property's setter does not execute. All that happens is the TextBox becomes outlined in red. I presume this is to indicate that it's an invalid value.

This isn't good enough though. I need to display a messagebox or some note to the user to inform them it's an invalid value. What do I need to do to make this happen?

Upvotes: 0

Views: 155

Answers (4)

Stephen
Stephen

Reputation: 509

You can add a validation error handler to the control or window.

In window constructor:

this.AddHandler(Validation.ErrorEvent, new RoutedEventHandler(OnValidationError));

Handler:

    private void OnValidationError(Object sender, RoutedEventArgs e)
    {
        if (e.OriginalSource is DependencyObject)
        {
            DependencyObject instance = e.OriginalSource as DependencyObject;
            if (Validation.GetHasError(instance))
            {
                System.Collections.ObjectModel.ReadOnlyObservableCollection<ValidationError> errors = Validation.GetErrors(instance);
                // todo build message from errors and display
            }
        }
    }

Upvotes: 0

Rhyous
Rhyous

Reputation: 6680

I have an article that covers what you are asking for. The title might not appear to match with what you are asking, but it happens to demo the feature you are asking for.

How to disable a Button on TextBox ValidationErrors in WPF

This will show you how to not only have the red around the TextBox but also how a message too.

Upvotes: 0

earthling42
earthling42

Reputation: 976

Another possibility would be to define the TextChanged event of the text box so that it does a Int32.Parse every time the text changes. It can then fire off a message box if the value exceeds 255.

If you want to be mean you can make the maximum length two characters long and force users to input the number in hex.

Upvotes: 1

ChrisF
ChrisF

Reputation: 137128

You need to add a Validation Summary control on the page.

This will be hidden by default, but when the validation error occurs (as in this case when a value greater than 255 is entered) it will appear telling the user what's wrong.

There are several such controls available for WPF, you will need to evaluate them and pick the one that works for you. You will probably need to set some attributes on the data layer to control the exact error message that's displayed.

Upvotes: 2

Related Questions