自定义TextBox的WPF验证ErrorTemplate

Duk*_*lus 7 validation wpf custom-controls

分支这个问题 -

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

<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>
Run Code Online (Sandbox Code Playgroud)

如果ViewModelProperty中存在验证错误,我的应用程序抛出异常 -

Key cannot be null.
Parameter name: key
Run Code Online (Sandbox Code Playgroud)

我不确定为什么会这样.是否需要执行某些操作才能将新错误模板分配给自定义控件?

更新:

我已经发现问题在于错误模板中的Tag属性.如果我删除标签,它就可以正常工作.

谢谢

Duk*_*lus 8

好吧,我设法解决问题的方法是删除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>
Run Code Online (Sandbox Code Playgroud)

我不明白的是,为什么它在使用AdornedElement关键字时表现不同,但在使用RelativeSource绑定Tag/Tooltip时工作正常.虽然问题已经解决,但我欢迎任何关于为什么会这样的想法.

谢谢

  • 我意识到这是一个老问题,但我猜你的第一个例子引发了一个Exception,因为`Validation.Errors`集合中没有错误,但你试图绑定到第一个的`ErrorContent`属性(不存在)错误.在您的解决方案中,您只选择在"HasError"属性为true时绑定到错误消息,因此,当集合中存在一个或多个错误时.即使在第二个示例中,您仍应看到Visual Studio的"输出"窗口中显示的"异常". (4认同)