TGills
TGills

Reputation: 126

TextBox validation not working as intended

I am having trouble implementing a number validator on a textbox in WPF. If the user enters something like abc into the textbox, an warning/error message should pop up. If they enter in 1.99, that should be fine. What is currently happening, from what I can tell, is that the validation isn't being triggered. The other problem is that on page load, I am setting the value of the textbox to a predefined value but when you see the page loaded, the textbox is empty. So instead of seeing something like 13.42 in the textbox, it's blank. However, when I remove the <TextBox.Text> part, the value appears.

Here's my regex validator class:

public class RegexValidation : ValidationRule
    {
        private string pattern;
        private Regex regex;

        public string Expression
        {
            get { return pattern; }
            set
            {
                pattern = value;
                regex = new Regex(pattern, RegexOptions.IgnoreCase);
            }
        }

        public RegexValidation() { }

        public override ValidationResult Validate(object value, CultureInfo ultureInfo)
        {
            if (value == null || !regex.Match(value.ToString()).Success)
            {
                return new ValidationResult(false, "The value is not a valid number");
            }
            else
            {
                return new ValidationResult(true, null);
            }
        }
    }

Following that, here are my page resources:

<Page.Resources>
        <system:String x:Key="regexDouble">^\d+(\.\d{1,2})?$</system:String>
        <ControlTemplate x:Key="TextBoxErrorTemplate">
            <StackPanel>
                <StackPanel Orientation="Horizontal">                    
                    <AdornedElementPlaceholder x:Name="Holder"/>
                </StackPanel>
                <Label Foreground="Red" Content="{Binding ElementName=Holder, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}"/>
            </StackPanel>
        </ControlTemplate>        
    </Page.Resources>  

Lastly, the textbox that requires validation and the button that shouldn't work if a number is not in the textbox:

<TextBox Name="txtItemPrice" Grid.Column="12" Grid.ColumnSpan="2" Grid.Row="4" HorizontalAlignment="Stretch" VerticalAlignment="Center" IsEnabled="False" Validation.ErrorTemplate="{StaticResource TextBoxErrorTemplate}">
            <TextBox.Text>
                <Binding Path="intPrice" UpdateSourceTrigger="PropertyChanged">
                    <Binding.ValidationRules>
                        <classobjects:RegexValidation Expression="{StaticResource regexDouble}"/>
                    </Binding.ValidationRules>
                </Binding>
            </TextBox.Text>
        </TextBox>
<Button Name="btnSaveChanges" Content="Save Changes" Grid.Column="4" Grid.Row="11" HorizontalAlignment="Stretch" VerticalAlignment="Center" Visibility="Hidden" Click="btnSaveChanges_Click"/>

Tutorials that I have tried following with no success:

Edit:

I tried something different with how I was trying to set the text. Instead of directly setting the textbox text, I tried to use the binding path property with the following code. However, I am still not having any results.

private string price;
public string intPrice
{
     get { return price; }
     set { price = value; }
}
private void fillInventoryInformation(Inventory i)
{
     //This method is called from the starter method on this page. 
     //Here I am setting the value of intPrice
     intPrice= (Convert.ToDouble(i.intPrice) / 100).ToString();  
     //This was how I was previously trying to set the value of the textbox  
     txtItemPrice.Text = (Convert.ToDouble(i.intPrice) / 100).ToString();    
}

Upvotes: 0

Views: 371

Answers (1)

TGills
TGills

Reputation: 126

Fixed my issue, and the validator works as intended. The issue was with how I was binding. I was trying to set the text of each textbox in the code behind and not using the binding path. Once I switched from going txtTextbox.Text = "123" to the following, everything fell into place and started working properly.

private void fillInventoryInformation(Inventory i)
{
    DataContext = i;
}

Upvotes: 0

Related Questions