I've been looking in StackOverflow, and several questions are done. But they don't work.
I have this PasswordBox
:
<PasswordBox Width="160"
HorizontalAlignment="Left"
Margin="10,3"
Name="textBoxUserPass"
local:PasswordBoxAssistant.BindPassword="True"
local:PasswordBoxAssistant.BoundPassword="{Binding Path=Password, UpdateSourceTrigger=Explicit,
ValidatesOnDataErrors=True, ValidatesOnExceptions=True}"
Validation.ErrorTemplate="{x:Null}" />
I first set the ValidationErrorTemplate="{x:Null}"
so first time I load the PasswordBox
it doesn't try to validate the box.
When I find a error, I try to change the Validation.ErrorTemplate
so it shows a red border (as the ErrorTemplate
I have defined) like this:
BindingExpression bePassword = textBoxUserPass.GetBindingExpression(PasswordBoxAssistant.BoundPassword);
if (bePassword != null)
{
bePassword.UpdateSource();
if (bePassword.HasError)
{
var validationError = new ValidationError(new ExceptionValidationRule(), bePassword);
Validation.MarkInvalid(bePassword, validationError);
validationError.ErrorContent = Cultures.Resources.MessageNoPassword;
var b = Resources["validationTemplate"] as ControlTemplate;
Validation.SetErrorTemplate(textBoxUserPass, b);
}
}
}
Where I have defined my validationTemplate on a ResourceDictionary.xaml
like this:
<Style x:Key="validationTemplate" TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<DockPanel LastChildFill="True">
<TextBlock DockPanel.Dock="Right"
Foreground="Red"
FontSize="12pt">
*
</TextBlock>
<Border BorderBrush="Red" BorderThickness="1" CornerRadius="5">
<AdornedElementPlaceholder />
</Border>
</DockPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
A regular box, as you can see.
My problem comes when trying to find this resource to change my Validation.ErrorTemplate
in code behind. I put a breakpoint, and this line:
var b = FindResource("validationTemplate") as ControlTemplate;
says that b is null. How I can find "validationTemplate"
and use it??