Josh
Josh

Reputation: 657

How to show a tooltip on invalid input into a textbox

I am trying to setup validation for a phone number field in a WPF application using MVVM. I have the textbox text bound but cant seem to figure out the logic involved in rejecting input and popping up a tooltip. Any suggestions would be appreciated.

   [Required]
    public string PhoneNumber
    {
        get
        {
            return EntityPhone.PhoneNumber;
        }
        set
        {
            int intValue = 0;
            if(!int.TryParse(value, out intValue))
            {
 //               ToolTip tt = new ToolTip();
 //               tt.Content = "Invalid Character. Please enter a valid 10-digit number";
            }
            EntityPhone.PhoneNumber = value;
            NotifyOfPropertyChange(() => PhoneNumber);
        }
    }

Upvotes: 1

Views: 1812

Answers (1)

Rachel
Rachel

Reputation: 132658

First you'll want to make your class inherit IDataErrorInfo, which is used by WPF for validation purposes.

public class MyClass : IDataErrorInfo
{
    ...

    #region IDataErrorInfo Members

    string IDataErrorInfo.Error
    {
        get { return null; }
    }

    string IDataErrorInfo.this[string columnName]
    {
        get
        {
            if (columnName == "PhoneNumber")
            {
                // Validate property and return a string if there is an error
                return "Some error";
            }

            // If there's no error, null gets returned
            return null;
        }
    }
    #endregion
}

Next, tell your binding that it should be validating the value when it changes

<TextBox Text="{Binding Path=PhoneNumber, ValidatesOnDataErrors=True}" ... />

And finally, create a validation template. Here's the style/template I usually use

<!-- ValidatingControl Style -->
<Style TargetType="{x:Type FrameworkElement}" x:Key="ValidatingControl">
    <Style.Triggers>
        <Trigger Property="Validation.HasError" Value="True">
            <Setter Property="ToolTip" Value="{Binding 
                Path=(Validation.Errors)[0].ErrorContent, 
                RelativeSource={x:Static RelativeSource.Self}}" />
        </Trigger>
    </Style.Triggers>
</Style>

Upvotes: 1

Related Questions