Jie*_*eng 16 validation wpf templates
为什么错误上没有工具提示文字?
<Style TargetType="{x:Type TextBox}">
<Setter Property="Validation.ErrorTemplate">
<Setter.Value>
<ControlTemplate>
<StackPanel>
<Border ...>
<AdornedElementPlaceholder ...
ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Border>
...
</StackPanel>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
Run Code Online (Sandbox Code Playgroud)
我也注意到了
<AdornedElementPlaceholder ...
ToolTip="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
Run Code Online (Sandbox Code Playgroud)
失败但是下面的成功,即使有相同的约束,为什么会这样呢?不AdornedElementPlaceholder参考文本框?即使它没有,也不应该出现工具提示吗?
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
Run Code Online (Sandbox Code Playgroud)
LPL*_*LPL 18
我知道我迟到了,但是让我分享一个我发现研究这个问题的解决方案:带工具提示的WPF自定义验证器.
在它的最简单的形式是ErrorTemplate只显示Tooltip与ErrorContent整个AdornedElement.
<ControlTemplate x:Key="validationTemplate">
<Grid Background="Transparent"
ToolTip="{Binding Path=/ErrorContent}">
<AdornedElementPlaceholder />
</Grid>
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)
但是当然你可以根据需要装饰它,例如Tooltip只用一个标记.
<ControlTemplate x:Key="validationTemplate">
<Grid>
<Ellipse Fill="Red" Opacity="0.8" Width="10" Height="10"
HorizontalAlignment="Right" VerticalAlignment="Top"
ToolTip="{Binding Path=/ErrorContent}" />
<AdornedElementPlaceholder />
</Grid>
</ControlTemplate>
Run Code Online (Sandbox Code Playgroud)
把它放进Template去Resources,你所要做的就是设置Validation.ErrorTemplate.
Validation.ErrorTemplate="{StaticResource validationTemplate}"
Run Code Online (Sandbox Code Playgroud)
甚至不再需要这种烦人的触发器.
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="True">
<Setter Property="ToolTip" Value="{Binding RelativeSource={RelativeSource Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
Run Code Online (Sandbox Code Playgroud)
您不能在AdornedElementPlaceholder上放置工具提示,我认为它根本不可见,它只是为使用它的人保留空间(在您的情况下为TextBox)。使用Snoop观察可视树,我们可以看到TemplatedAdorner最终位于VisualTree中与TextBox不同的位置,因此现在我们可以找到从VisualTree中找到TextBox的方式。我们可以通过AdornedElement找到它,但仍然无法设置工具提示。

TemplatedAdorner中唯一可见的是边框。边界知道其子级-TemplatedAdorner-而后者又知道其AdornedElement-文本框。因此,我们可以以此为边界设置工具提示。(但是,此绑定似乎无法更新边框的工具提示。当我用Snoop看着它并显示之后,它可以工作。)
<Border BorderBrush="Red"
BorderThickness="4"
ToolTip="{Binding RelativeSource={RelativeSource self},
Path=Child.AdornedElement.(Validation.Errors)[0].ErrorContent}">
Run Code Online (Sandbox Code Playgroud)
因此,TextBox具有其AttachedProperty Validation,在其中我们可以找到ErrorContent,因此它必须像在上一个示例中所做的那样设置自己的ToolTip,否则它将无法正常工作。