自定义文本框的WPF验证错误模板

8

这个问题分支出来 -

当我像这样将验证错误模板附加到我的自定义文本框时 -

<local:CustomTextBox CustomText="{Binding ViewModelProperty}" Validation.ErrorTemplate="{StaticResource errorTemplate}"/>

<ControlTemplate x:Key="errorTemplate">
    <DockPanel>
        <Border BorderBrush="Red" BorderThickness="1">
            <AdornedElementPlaceholder x:Name="controlWithError"/>
        </Border>
        <TextBlock Foreground="Red" FontSize="20" FontFamily="Segoe UI" Margin="3,0,0,0"  MouseDown="Exclamation_MouseDown"  Tag="{Binding AdornedElement.(Validation.Errors)[0].ErrorContent, ElementName=controlWithError}">!</TextBlock>
    </DockPanel>
</ControlTemplate>

如果ViewModelProperty存在验证错误,我的应用程序将抛出异常 -
Key cannot be null.
Parameter name: key

我不确定为什么会发生这种情况。是否需要进行某些操作才能将新的错误模板分配给自定义控件?
更新:
我已经发现问题出在错误模板的标签属性上。如果我移除标签,它就可以正常工作。
谢谢。
1个回答

11

好的,我解决了这个问题的方式是去掉AdornedElement关键字,并将错误模板更改为以下内容:

<local:CustomTextBox CustomText="{Binding ViewModelProperty}">
    <Validation.ErrorTemplate>
        <ControlTemplate>
            <DockPanel>
                <Border BorderBrush="Red" BorderThickness="1">
                    <AdornedElementPlaceholder x:Name="controlWithError"/>
                </Border>
                <TextBlock Foreground="Red" FontSize="20" FontFamily="Segoe UI" Margin="3,0,0,0"  MouseDown="Exclamation_MouseDown">!</TextBlock>
            </DockPanel>
        </ControlTemplate>
    </Validation.ErrorTemplate>
    <local:CustomTextBox.Style>
        <Style TargetType="{x:Type local:CustomTextBox}">
            <Style.Triggers>
                <Trigger Property="Validation.HasError" Value="true">
                    <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
                    <Setter Property="Tag" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </local:CustomTextBox.Style>
</local:CustomTextBox>

我不理解的是,使用AdornedElement关键字时,它为什么行为不同,但是使用RelativeSource绑定标签/工具提示时却正常工作。虽然问题得到了解决,但我欢迎任何有关原因的想法。

谢谢


6
我知道这是一个旧问题,但我猜测你第一个例子抛出了一个异常是因为在Validation.Errors集合中没有错误,但你试图绑定到第一个(不存在的)错误的ErrorContent属性。在你的解决方案中,只有当HasError属性为true时,也就是说集合中有一个或多个错误时,才选择绑定到错误信息。即使在这个第二个例子中,你仍然会在Visual Studio的输出窗口中看到异常。 - Sheridan

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接