Mark W
Mark W

Reputation: 811

TextBox validation problem

I am trying to get a textbox to validate in WPF. The problem is when there is no data entered into the textbox which should cause a validation error, no validataion error shows. Can someone give me some help? Thank you in advance. Here is my code

public class User
    {
        private string _name;

        public string myName
        {
            get { return _name; }
            set
            {
                _name = value;
                if (String.IsNullOrEmpty(value))
                {
                    throw new ApplicationException("User name is mandatory.");
                }
            }
        }
    }
<TextBox Height="23"
                 HorizontalAlignment="Right"
                 Margin="0,0,194,250" Name="textBox1"
                 VerticalAlignment="Bottom"
                 Width="120" >
                <TextBox.Text>
                    <Binding Path="myName" >
                        <Binding.ValidationRules>
                            <ExceptionValidationRule />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
        </TextBox>

Edit: I really was having a problem with binding. I fixed my code, here it is: I started with creating a user, and an error template:

<local:User x:Key="myDataSource" myName="Enter Name" />

        <ControlTemplate x:Key="validationTemplate">
            <DockPanel>
                <TextBlock Foreground="Red" FontSize="20">!!!</TextBlock>
                <AdornedElementPlaceholder/>
            </DockPanel>
        </ControlTemplate>

I then had the save button disabled if there were validation errors

<Button Content="Write Kml"
                Height="23"
                HorizontalAlignment="Right"
                Margin="0,0,12,41"
                Name="writeKml"
                VerticalAlignment="Bottom"
                Width="75" Click="button2_Click" >
            <Button.Style>
                <Style TargetType="{x:Type Button}">
                    <Setter Property="IsEnabled" Value="false" />
                    <Style.Triggers>
                        <DataTrigger Binding="{Binding ElementName=textBox1, Path=(Validation.HasError)}" Value="false">
                            <Setter Property="IsEnabled" Value="true" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </Button.Style>
        </Button>

Then I fixed the textBox to allow for proper validation

<TextBox Height="23"
                 HorizontalAlignment="Right"
                 Margin="0,0,194,250"
                 Name="textBox1"
                 VerticalAlignment="Bottom"
                 Validation.ErrorTemplate="{StaticResource validationTemplate}"
                 Width="120" >
                <TextBox.Text>
                    <Binding
                        Source="{StaticResource myDataSource}"
                        Path="myName"
                        UpdateSourceTrigger="PropertyChanged"
                        ValidatesOnExceptions="True"
                        ValidatesOnDataErrors="True" >
                        <Binding.ValidationRules>
                            <local:CheckName />
                        </Binding.ValidationRules>
                    </Binding>
                </TextBox.Text>
        </TextBox>

here is the code behind

public class User
    {
        private string _name;

        public string myName
        {
            get { return _name; }
            set { _name = value; }
        }
    }

    public class CheckName : ValidationRule
    {
        public override ValidationResult Validate(object value, CultureInfo cultureInfo)
        {
            if (value == null || object.Equals(value, string.Empty))
            {
                return new ValidationResult(false, "Please enter user name");
            }

            if (value.ToString() == "Enter Name")
            {
                return new ValidationResult(false, "Please enter user name");
            }

            return new ValidationResult(true, null);
        }
    }

finally I added code to the window loaded routine to force validation

private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            textBox1.GetBindingExpression(TextBox.TextProperty).UpdateSource();
        }

I hope this helps anyone who is trying to do validation of a textbox in WPF.

Upvotes: 1

Views: 702

Answers (1)

Phil Sandler
Phil Sandler

Reputation: 28046

Your User class needs to implement INotifyPropertyChanged in order for it to support databinding in WPF. You will likely need to do a bit of reading on WPF and databinding, as it is fundamental knowledge needed to be able to build WPF (or Silverlight) applications.

Couple links to get you started:

Data Binding Overview

INotifyPropertyChanged Interface

Upvotes: 2

Related Questions