从这个问题分支出来 -
当我像这样将验证错误模板附加到我的自定义文本框时 -
<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
我不确定为什么会发生这种情况。是否需要进行某些操作才能将新的错误模板分配给自定义控件?
更新:
我已经发现问题出在错误模板的标签属性上。如果我移除标签,它就可以正常工作。
谢谢。
Validation.Errors
集合中没有错误,但你试图绑定到第一个(不存在的)错误的ErrorContent
属性。在你的解决方案中,只有当HasError
属性为true时,也就是说集合中有一个或多个错误时,才选择绑定到错误信息。即使在这个第二个例子中,你仍然会在Visual Studio的输出窗口中看到异常。 - Sheridan