Text box not showing Red Validation Error in WPF - c#

We are currently writing a GUI application using WPF and .Net4.5.
One of our pages contains a TabControl with custom UserControls as TabItems. These UserControls just contain a list of editable TextBoxes. The Textboxes have a custom ValidationRule that validates the text based on a regular expression. The issue is that these editable text boxes are bound to Properties that get loaded at startup with default values from a text file/database.
I need validation to occur before a text box has focus, or before it is edited, to ensure that the values that were entered in the text file/database were entered correctly. Currently, when I select a tab item the text boxes are not displaying the red validation error box, even though it seems validation is running correctly. Only after I click an item with a Validation error do I see the associated red box.
I am using UpdateSourceTrigger="PropertyChanged" and I can debug and see that the validation code is running at the correct time, but still the red boxes will not display. I even added code to re-fire the 'Property changed' events on the bound properties whenever the TabItem gains focus - but this still does not help. Here is an example of one of the TextBoxes that is not showing the validation:
<TextBox x:Name="TextBox1" Margin="10,5,5,5" Width="150" MaxLength="5" Style="{StaticResource ServiceEntryTextBox}">
<TextBox.Text>
<Binding Path="TexBox1BoundProperty" Converter="{StaticResource DoubleConverter}" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" ValidatesOnExceptions="True">
<Binding.ValidationRules>
<validation:StringRegexFormatValidation RegexPattern="^[0-9]{0,1}.{0,1}[0-9]{1,3}$" ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Is there another piece I am missing?

Can you try placing your TextBox inside an AdornerDecorator? I need to dig out the source for this but I have seen issues before where controls inside a Tab control do not render the validation correctly.
e.g.
<AdornerDecorator>
<TextBox x:Name="TextBox1" Margin="10,5,5,5" Width="150" MaxLength="5" Style="{StaticResource ServiceEntryTextBox}">
<TextBox.Text>
<Binding Path="TexBox1BoundProperty" Converter="{StaticResource DoubleConverter}" UpdateSourceTrigger="PropertyChanged" ValidatesOnDataErrors="True" ValidatesOnExceptions="True">
<Binding.ValidationRules>
<validation:StringRegexFormatValidation RegexPattern="^[0-9]{0,1}.{0,1}[0-9]{1,3}$" ValidatesOnTargetUpdated="True"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</AdornerDecorator>
Further help for debugging
I have also seen issues when binding directly to a DependencyProperty. The issue I saw was I was raising INotifyPropertyChanged in order to trigger the validation to be processed (which worked fine in .NET 4.0) however since .NET 4.5 you cannot use INotifyPropertyChanged for triggering validation on a DependencyProperty.

Related

Implementing validation for Texboxes in Item Templates

I think it is all bout manually trigerring validation for data template.
For example I have my checklistbox (it is from Xceed wpf extended toolkit, but it doesnt matter. It can be a simple listbox for the sake of example):
<xctk:CheckListBox Name="myCheckListBox" ItemsSource="{Binding Fields}" SelectedValue="{Binding SelectedValue}" Margin="10,10,10,72">
<xctk:CheckListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Width="250" Text="{Binding Field.Symbol}"/>
<Label Content="Value:" Visibility="{Binding SelectedValueVisibility}"/>
<TextBox Name="myTextBox" Width="100" Visibility="{Binding SelectedValueAppVisibility}"
Validation.ErrorTemplate="{StaticResource validationErrorTemplate}" >
<TextBox.Text>
<Binding Path="TextValue" Mode="TwoWay" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<my:EmptyTextValidator></my:EmptyTextValidator>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
</StackPanel>
</DataTemplate>
</xctk:CheckListBox.ItemTemplate>
</xctk:CheckListBox>
I have my EmptyTextValidator class similiar to:
https://learn.microsoft.com/en-us/dotnet/framework/wpf/data/how-to-implement-binding-validation
For clarification: "Value: {TextBox}" appears only when an item is checked.
The problem is the same as if it was a simple Listbox and all the textboxes would be visible from the beginning.
What is needed:
Show validation errors on Button_click.
The problem:
Validation works only after you enter something.
When user loads my control and instantly clicks "OK", validation errors are not displayed.
To trigger validation manually I need a "static" textbox:
textBox1.GetBindingExpression(TextBox.TextProperty).UpdateSource();
I am unable to do it with a texbox in template.
This is also the reason why I am unable to do it throught e.g IDataErrorInfo.
You could implement the INotifyDataErrorInfo interface in the class where the TextValue property is defined and raise the ErrorsChanged event whenever you want to invalidate the TextBox. Please refer to the following TechNet article for a sample implementation: https://social.technet.microsoft.com/wiki/contents/articles/19490.wpf-4-5-validating-data-in-using-the-inotifydataerrorinfo-interface.aspx.
So in your Button click event handler, or in your command, you could iterate through the items in your Fields collection and call a method or something of each of these objects that performs the validation and raises the ErrorsChanged. This should cause the Validation.Error template of the invalid TextBox elements in the ListView to be displayed as expected.

WPF validation without updating the data source

I have a TextBox displaying the time part of a DateTime:
<TextBox HorizontalAlignment="Left" Height="23" Margin="0,13,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" Validation.Error="Validation_OnError">
<TextBox.Text>
<Binding Path="MyDate" StringFormat="HH:mm" NotifyOnValidationError="True" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<c:TimeValidator></c:TimeValidator>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Is it possible to do the validation on property change, and the conversion on lost focus?
I want to have the validation on property changed, but I want to have my data source updated on lost focus. Otherwise, the converter will kick in while the user is editing in the TextBox. This might be a problem if the values is 10:50 and the user deletes the last number, so that the value becomes 10:5. The converter will then convert this to 10:50. This is okay to do on lost focus, but not on property changed. But for the sake of the validator, i want to validate on property change so the user have the red border as long as the entered value is not valid.
Yes! I was just wrestling with this. AFAIK, there is no XAML combination for this--it must be done in the codebehind, and you need a direct reference to the element.
Element.GetBindingExpression(PropertyName).ValidateWithoutUpdate();
You'll probably want to check that GetBindingExpression doesn't return null; this will run any converters you have attached (presumably to supply the converted value to converters with ValidationStep set to ConvertedProposedValue), but will not update the source. And, of course, you'll have to call this in some event, perhaps TextChanged or somesuch. Here is the MSDN documentation for it: https://msdn.microsoft.com/en-us/library/system.windows.data.bindingexpressionbase.validatewithoutupdate(v=vs.110).aspx
Use this code:
BindingExpression expression =
txtStudentName.GetBindingExpression(TextBox.TextProperty);
expression.ValidateWithoutUpdate();
If you want to update it's source after check use this code:
BindingExpression expression =
txtStudentName.GetBindingExpression(TextBox.TextProperty);
expression.ValidateWithoutUpdate();
if (expression!=null && !expression.HasError)
expression.UpdateSource();

Using WPF validation

I have a dialog in my project that the user enters some values in and when he hits OK I add an item to my database. I am using Entity Framework, so my adding to database code is something like this:
TransactionItem _item = new TransactionItem();
_item.DoctorID = (int)cmbDoctor.SelectedValue;
_item.TransactionCategoryID = (int)_dlg.cmbCat.SelectedValue;
_item.TransactionMethodID = (int)_dlg.cmbMethod.SelectedValue;
_item.Amount = int.Parse(_dlg.txtAmount.Text);
_item.DocumentID = _dlg.txtDocNum.Text;
_item.Info = _dlg.txtInfo.Text;
_item.Date = _dlg.dteDate.SelectedDate.ToString();
_db.TransactionItems.Add(_item);
_db.SaveChanges();
But the problem is there is nothing to bind and enable validating. I have tried making an empty object in my window and bind text box to it, but it had its own problems and didn't work as expected. I just want to when users enter values or when he hits OK, check if all of fields are valid (for example one of problems was if the user didn't enter any value, it is still valid even though the stringnotnull validator is enabled, but the most important problem was that it automatically set the textbox's text to null and mark it as a null value).
And I have made my own validator and here is a example of how I implemented them on one of my textboxes:
<TextBox Name="txtAmount" HorizontalAlignment="Left" Height="23" Margin="83,169,0,0" VerticalAlignment="Top" Width="224" Tag="T">
<TextBox.Text>
<Binding Path="myitem" ElementName="myWindow" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<Validators:StringNullValidationRule/>
<Validators:IsNumericValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Why don't you create a property in your viewmodel for each value the user needs to enter, and bind to it? Then you could use these properties when adding an item. For example:
ViewModel:
public int Amount { get; set; }
...
public void AddItem()
{
TransactionItem _item = new TransactionItem();
// ...
_item.Amount = Amount;
}
XAML:
<TextBox Name="txtAmount" HorizontalAlignment="Left" Height="23" Margin="83,169,0,0" VerticalAlignment="Top" Width="224" Tag="T">
<TextBox.Text>
<Binding Path="DataContext.Amount" ElementName="myWindow">
<Binding.ValidationRules>
<Validators:StringNullValidationRule/>
<Validators:IsNumericValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
I also recommend having a look at the INotifyDataErrorInfo interface (or the IDataErrorInfo interface if you're using .NET 4.0 or lower) to implement validations.
Use the IDataErrorInfo interface. You can implement it in your ViewModel or your Model class depending on your design. An example of how you can do it is in WPF: Validation made easy with IDataErrorInfo.
And I recommend you read this great Josh Smith article: WPF Apps With The Model-View-ViewModel Design Pattern. There you can see a good example of validation.

Custom ValidationRules inside Expander.Header Binding not firing

I am having trouble getting a custom ValidationRule to fire, when it is associated with an Expander.Header binding. In fact, the only place I can seem to get these custom rules to fire is in a DataGrid.RowValidationRules block...
The expander is defined in my Window XAML file like so;
<Expander Style="{StaticResource ValidatedSecondLevelExpanderStyle}">
<Expander.Header>
<Binding Path="Name" Mode="OneWay" ValidatesOnDataErrors="True" NotifyOnValidationError="True">
<Binding.ValidationRules>
<ValidationRules:BoundObjectIsValid />
</Binding.ValidationRules>
</Binding>
</Expander.Header>
</Expander>
The bound property 'Name' is displayed correctly, but the validation rule 'BoundObjectIsValid' does not get invoked. Is this possible, and if so, what am I missing?
I know that I could alternately implement IDataErrorInfo on the bound object, however the object can't sensibly validate itself without some context that is provided by other parts of the system. Refactoring is possible, but I'd love to get the ValidationRules to work first!
Refer to the msdn.
The binding engine checks each ValidationRule that is associated with a binding every time it transfers an input value, which is the binding target property value, to the binding source property.
So here in your case, you don't have an inpurt value being transfered to the source property since your Expander.header is not a control which you can use to input values.
Edit: But there is a property named ValidatesOnTargetUpdated' in the ValidationRule. When setting it to true, the validationrule will be applied when the target property is updated

TextBox Placeholder text while also Binding to ListBox.SelectedItem

How can I still have a Placeholder text (.Text = "Whatever") while also binding the textbox to a ListBox's Selected Item?
When do you want this placeholder text to display? When there is no SelectedItem?
You could use PriorityBinding which will allow you to provide a list of bindings and it will use the first that produces a result.
Something like:
<TextBox>
<TextBox.Text>
<PriorityBinding>
<Binding Path="myListBox.SelectedItem"/>
<Binding Source="Default Text"/>
</PriorityBinding>
</TextBox.text>
</TextBox>

Categories

Resources