1

我正在尝试通过代码而不是 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 布局,并在 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);

我没有得到任何错误验证,甚至没有默认模板。

我错过了什么吗?

4

2 回答 2

2

当你这样做时

ControlTemplate ct = this.Resources["validationErrorTemplate"] as ControlTemplate;
Validation.SetErrorTemplate(stb, ct);

甚至没有默认的错误模板,很可能ct是 null

确保“validationErrorTemplate”存储在 Window ( this) 资源中。如果模板存储在资源的某个地方,可以通过FindResource方法找到

ControlTemplate ct = stb.FindResource("validationErrorTemplate") as ControlTemplate;
Validation.SetErrorTemplate(stb, ct);
于 2016-05-11T11:46:48.553 回答
1

我说得对SearchTextBoxTextBox?然后将绑定更改为:

stb.SetBinding(TextBox.TextProperty, bindingStb);

更新:

ControlTemplate ct = FindResource("validationErrorTemplate") as ControlTemplate;
Validation.SetErrorTemplate(stb, ct);
于 2016-05-11T10:14:06.307 回答