WPF: Initializing a TextBox and binding it to a validation rule - wpf

I try to validate the IP-Address a user enters into a text box of a WPF Dialog. The text box is supposed to be initialized with 127.0.0.1. This is the XAML:
<TextBox
Height="23"
Width="98"
VerticalAlignment="Top"
HorizontalAlignment="Left"
Name="ip_address"
Text="127.0.0.1">
<TextBox.Text>
<Binding Path="Left" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<local:IPValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
This attempt to bind the text box to the validation rule causes an error, because the attribute Text already has the value 127.0.0.1. My question is this: How can I achieve initializing and binding simultaneously?
Regards, RSel
PS: Initializing the text box in Window_Loaded doesn't work either. The box just remains empty. Without the binding to the rule it works.

A couple options:
Set an initial value in the property that the textbox is bound to. The binding should pick this up when the control loads. I'm not sure if this meets your goals though.
Use the TargetNullValue property of the binding object to specify what to show when the source is null.
Here's MSDN on option 2:
http://msdn.microsoft.com/en-us/library/system.windows.data.bindingbase.targetnullvalue.aspx

Related

ValidationRule Red Border Issue

In my WPF Application, I have created ValidationRules for my TextBoxes so that it will not allow an empty string which works fine and shows a red border with text telling the user it can not be empty. When the application launches, all the fields are blank waiting for input but I still see the red border around them. Is this normal behavior? Note: I would prefer it firing after either a propertychange event or lostfocus event fires when the user using the form not when the form initially loads.
Example of the validation I am doing:
<TextBox x:Name="itemNum" HorizontalAlignment="Left" Height="23" Margin="82,58,0,0" VerticalAlignment="Top" Width="90"
HorizontalContentAlignment="Left" VerticalContentAlignment="Center" PreviewKeyDown="ItemNum_PreviewKeyDown"
PreviewTextInput="ItemNum_PreviewTextInput" TabIndex="0" Validation.ErrorTemplate="{StaticResource validationErrorTemplate}">
<TextBox.Text>
<Binding Path="rxID" Mode="TwoWay" StringFormat="{}{0:#}" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<MY:TextBoxNotEmptyValidationRule x:Name="rxIDValidation" ValidatesOnTargetUpdated="True" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
My TextBoxNotEmptyValidationRule Class:
public override ValidationResult Validate(object value, System.Globalization.CultureInfo cultureInfo)
{
string str = value as string;
if (string.IsNullOrEmpty(str))
{
return new ValidationResult(false, "Value CAN NOT BE empty");
}
return ValidationResult.ValidResult;
}
According to your logic, it seems that it is normal. Lets define a bool flag and set it false or true, does not matter, than when application is run and check the flag, if flag value is initial value do not do anything. Beside this, you "if" check needs to check also focused element. If focused element is our textbox and your flag is not initial value so you can change the textblock border.
You can look at the following link :
Validation on Load
Ideally this is the normal behavior in XAML applications if you use IDataErorInfo or INotifyDataErrorInfo . you can use beginInit and EndInit to achieve your desired output.

Insert operations and ValidatesOnDataErrors: controls reported to be invalid as soon as they are displayed

In wpf controls, such as TextBox, you can set ValidatesOnDataErrors=true.
You can also want to change the default value for UpdateSourceTrigger.
For insert operations the textbox initial value is often empty, so its content is supposed to be not valid and it will be rendered with a red border (sure you can override this with styles and templates and obtain what you want). My desired behavior is to validate the content of a control only after the user has changed its content or when he tries to save the data.
It seems to me that the only way to achieve this is to set UpdateSourceTrigger=Explicit, which is not very friendly with pure MVVM.
I have already read the following article, but I'm looking for something simpler.
http://www.shujaat.net/2011/01/updatesourcetrigger-explicit-for-mvvm.html
Thanks
Filippo
Set DataErrorValidationRule like this:
<TextBox>
<TextBox.Text>
<Binding Path="PropertyName" UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<DataErrorValidationRule ValidatesOnTargetUpdated="False"/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>

wpf validation rules problem with textbox

I created a class IntegersValidationRule which inherits from ValidationRule. Now I don't know what code should I write in XAML. That's what I have:
<TextBox Name="defaultTxt"
Height="23" Width="200">
<TextBox.Text>
<Binding UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<what:IntegersValidationRule/>
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
I know that either I'm so stupid that I can't understand in many tutorials what Path in Binding property means, why should we use Binding here when there's no binding required and what should I use instead of 'what' word inside Binding.ValidationRule.
what is an xmlns (see MSDN) which needs to point to the namespace in which your validation rule class is declared, e.g.
xmlns:what="clr-namespace:MyApp.MyValidationRules"
If you add no Path (- how about reading this if you do not understand it? -) the binding will bind to the current DataContext, whatever that may be in your case.
Question 1: validators work on bindings. That is why you specify the rule on a binding. As soon as then value will be updated to the source (object that the control binds to) the rule is checked.
Question 2: See H.B. 's answer

WPF Textbox Binding not Responding when ValidationRule Fired

I have a textbox that has a ValidationRule applied to it:
<TextBox Style="{StaticResource StandardTextBox}"
Grid.Column="1" Grid.Row="4"
IsReadOnly="{Binding SaveModeText}"
MaxLength="50">
<TextBox.Text>
<Binding Path="Individual.SurName"
UpdateSourceTrigger="PropertyChanged"
ValidatesOnDataErrors="True"
ValidatesOnExceptions="True"
NotifyOnValidationError="True">
<Binding.ValidationRules>
<valid:RequiredTextBoxValidationRule
ErrorMessage="Please enter a last name" />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
When the page loads the textbox contains the correct value based on its binding. If I delete the value from the textbox the ValidationRule fires properly and I see the error message as expected. My application contains a "Discard Changes" button which reloads the DataContext. The hope was it would reset all of the bindings and once again this textbox would display the original value. For some reason, all other values on the page that do not have a ValidationRule associated with them get reset properly, but this textbox does not.
If I remove the ValidationRule from the XAML the value resets properly. If I handle validation through IDataErrorInfo, the validation fires properly and the value resets properly. Because I have used ValidationRules throughout my application, I was wondering if anyone had come across this issue and resolved it. At this point I would prefer to stick with the implemented ValidationRules if possible, instead of switching everything over to IDataErrorInfo.
Since your you are modifying the value in code, wouldn't you need to have Mode=TwoWay in your binding for it to update? I don't have time to dig in and see if that's what's wrong, but it may be a place to start.

WPF TexBox TwoWay Binding Problem when ValidationRules used

I seem to have a problem with TwoWay DataBinding - my application has a window with a bunch of textboxes that allow to edit values of the properties they are bound to. Everything works well except for textboxes that also have a validation rule defined, in which case no text is displayed in the textbox when the window opens (binding back-to-source still works fine for those). If I remove Validation rule, everything's back to normal. I searched for an answer to this for a few hours now, but somehow did not even find anyone else complaining of the same issue. I am completely new to WPF, and I am sure it is just a silly mistake I have somewhere in my code... I will greatly appreciate any feedback...
<TextBox Margin="40,2,20,0" Grid.Column="0" Grid.Row="1" Background="#99FFFFFF" >
<Binding Path="LastName" Mode="TwoWay" ValidatesOnDataErrors="true" UpdateSourceTrigger="LostFocus" >
<Binding.ValidationRules>
<validation:StringNameValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox>
It would be nice to know what your binding source is, does it implement INotifyPropertyChanged for example?
Without nothing that, the only thing I can think of is the NotifyOnValidationError property on the binding class. Try setting it to true.

Resources