摘自this问题 -
将验证错误模板附加到我的自定义文本框 -
<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
我不确定为什么会这样。是否需要执行某些操作才能将新错误模板分配给自定义控件?
更新:
我已经发现问题出在错误模板中的Tag属性上。如果我删除了Tag,它就可以正常工作。
由于
答案 0 :(得分:7)
好吧,我设法解决问题的方法是删除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绑定Tag / Tooltip时工作正常。虽然问题已经解决,但我欢迎任何有关为何发生这种情况的想法。
由于