[英]WPF Validation ErrorTemplate for Custom TextBox
分支这个问题 -
将验证错误模板附加到我的自定义文本框时 -
<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属性。 如果我删除标签,它就可以正常工作。
谢谢
好吧,我设法解决问题的方法是删除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时工作正常。 虽然问题已经解决,但我欢迎任何关于为什么会这样的想法。
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.