1
我一直在尋找StackOverflow,並完成了幾個問題。但他們不工作。如何在代碼中設置Validation.ErrorTemplate?
我有這個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}" />
我首先設置ValidationErrorTemplate="{x:Null}"
所以我第一次加載PasswordBox
它不嘗試驗證框。
當我發現一個錯誤,我試圖改變Validation.ErrorTemplate
所以它顯示了一個紅色的邊框(作爲ErrorTemplate
我已經定義)是這樣的:
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);
}
}
}
如果我定義我的validationTemplate上ResourceDictionary.xaml
是這樣的:
<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>
一個普通的盒子,你可以看到。
我的問題來了當試圖找到此資源在代碼後面更改我的Validation.ErrorTemplate
。我把一個斷點,這條線:
var b = FindResource("validationTemplate") as ControlTemplate;
說b爲空。我如何才能找到"validationTemplate"
並使用它?
其實我這一行解決它: VAR模板= FindResource( 「validationTemplate」)作爲控件模板; Validation.SetErrorTemplate(textBoxUserPass,template); – Sonhja 2013-02-27 17:31:21
然後'FindResource'似乎更聰明,那麼我認爲,因爲它是爲你做演員。 – LPL 2013-02-27 18:19:27
但沒有你的評論我不會解決我的問題,所以我認爲是你解決了我的問題。我會將你的答案標記爲好的並編輯我的帖子以適應未來的用戶;) – Sonhja 2013-02-27 18:26:34