如何在Style内的ControlTemplate中获取应用该Style的TextBox控件
解决ErrorTemplate中控件绑定原TextBox ToolTip的问题
你遇到的核心问题是:Validation.ErrorTemplate的ControlTemplate上下文并非目标TextBox,这里的TemplatedParent指向的是负责渲染错误提示的Adorner(装饰器),而非应用该Style的TextBox,所以绑定TemplatedParent.ToolTip会返回空白。
解决方案
通过AdornedElementPlaceholder的AdornedElement属性绑定原TextBox的ToolTip即可。AdornedElementPlaceholder的作用就是定位到被装饰的目标控件(即你的TextBox),通过它可以直接获取原控件的所有属性。
修改后的完整Style代码如下:
<Style x:Key="TextBoxInError" TargetType="TextBox"> <Setter Property="VerticalContentAlignment" Value="Center" /> <Setter Property="Validation.ErrorTemplate"> <Setter.Value> <ControlTemplate> <Grid VerticalAlignment="Center" HorizontalAlignment="Right" Name="TemplateGrid"> <TextBlock HorizontalAlignment="Right" Margin="10,0,10,0" VerticalAlignment="Center" Foreground="Red" FontSize="20" FontFamily="Segoe MDL2 Assets" Text="" PreviewMouseDown="ExclamationPointMouseDown" ToolTip="{Binding ElementName=placeholder, Path=AdornedElement.ToolTip}"> </TextBlock> <!-- 给AdornedElementPlaceholder添加Name,用于绑定 --> <AdornedElementPlaceholder x:Name="placeholder" /> </Grid> </ControlTemplate> </Setter.Value> </Setter> <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="BorderBrush" Value="Red" /> <Setter Property="BorderThickness" Value="2" /> </Trigger> <Trigger Property="Validation.HasError" Value="false"> <Setter Property="ToolTip" Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=Tag}" /> <Setter Property="BorderBrush" Value="Gainsboro" /> <Setter Property="BorderThickness" Value="1" /> </Trigger> </Style.Triggers> </Style>
说明
- 给
AdornedElementPlaceholder添加x:Name="placeholder",通过ElementName绑定到它的AdornedElement属性,就能获取到原TextBox的ToolTip值。 - 这样修改后,模板内的红色感叹号控件会同步显示TextBox的ToolTip,不管是错误状态下的错误提示,还是正常状态下的Tag值,都无需逐个手动设置20多个TextBox。
内容的提问来源于stack exchange,提问作者nadim-241
相关产品推荐
相关产品推荐

