我试图通过代码向表单添加一些文本框,而不是XAML。并使用错误验证。我有以下代码:
SearchTextBox stb = new SearchTextBox()
{
Name = "stbRelatorio_" + id
};
// Create a new Binding.
Binding bindingStb = new Binding();
bindingStb.Source = model;
bindingStb.Path = new PropertyPath("ReportFile[" + id + "]");
stb.SetBinding(SearchTextBox.FileNameProprety, bindingStb);
BindingExpression bindingExpression =
BindingOperations.GetBindingExpression(stb, SearchTextBox.FileNameProprety);
BindingExpressionBase bindingExpressionBase =
BindingOperations.GetBindingExpressionBase(stb, SearchTextBox.FileNameProprety);
ValidationError validationError =
new ValidationError(new ExceptionValidationRule(), bindingExpression);
Validation.MarkInvalid(bindingExpressionBase, validationError);
ControlTemplate ct = this.Resources["validationErrorTemplate"] as ControlTemplate;
当我这样做时,我会在没有插入文字的情况下获得默认行为(这是我的错误案例)。文本框周围的红色框。我现在想要的是使用自定义的Adorner Layout,我在XAML上构建它
<ControlTemplate x:Name="validationErrorTemplate" x:Key="validationErrorTemplate">
<DockPanel>
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top">
<Grid Width="12" Height="12">
<Ellipse Width="12" Height="12"
Fill="Red" HorizontalAlignment="Center"
VerticalAlignment="Center"></Ellipse>
<TextBlock Foreground="White" FontWeight="Heavy"
FontSize="8" HorizontalAlignment="Center" VerticalAlignment="Center" TextAlignment="Center"
ToolTip="{Binding ElementName=ErrorAdorner, Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
X
</TextBlock>
</Grid>
<TextBlock Foreground="Red" FontWeight="12" Margin="2,0,0,2"
Text="{Binding ElementName=ErrorAdorner,
Path=AdornedElement.(Validation.Errors)[0].ErrorContent}">
</TextBlock>
</StackPanel>
<AdornedElementPlaceholder x:Name="ErrorAdorner" />
</DockPanel>
</ControlTemplate>
但是当我尝试设置ErrorTemplate时:
Validation.SetErrorTemplate(stb, ct);
我没有得到任何错误验证,甚至没有默认模板。
我错过了什么吗?
答案 0 :(得分:2)
当你做
时ControlTemplate ct = this.Resources["validationErrorTemplate"] as ControlTemplate;
Validation.SetErrorTemplate(stb, ct);
并且甚至没有默认错误模板,ct
可能为空
确保&#34; validationErrorTemplate&#34;存储在Window(this
)资源中。如果模板存储在资源中的某个位置,则可以通过FindResource
方法
ControlTemplate ct = stb.FindResource("validationErrorTemplate") as ControlTemplate;
Validation.SetErrorTemplate(stb, ct);
答案 1 :(得分:1)
我是否正确SearchTextBox
是从TextBox
继承的?
然后更改绑定到此:
stb.SetBinding(TextBox.TextProperty, bindingStb);
<强>更新强>
ControlTemplate ct = FindResource("validationErrorTemplate") as ControlTemplate;
Validation.SetErrorTemplate(stb, ct);