Search code examples
c#.netwpfxamlerrortemplate

Binding FontSize of TextBlock in Validation.ErrorTemplate


I declared a simple Validation.ErrorTemplate for TextBox as the following.

<Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <DockPanel LastChildFill="True">
                    <TextBlock Text="!" DockPanel.Dock="Right" 
                               FontSize="{TemplateBinding TextBox.FontSize}" 
                               Foreground="Red"/>
                    <AdornedElementPlaceholder  Name="adornerPlaceholder" />
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

I expect that the font size of the exclamation mark will be the same font(edited) size as TextBox, but it doesn't result in the expectation and always gets the default font size. Furthermore, I tried Binding using RelativeSource={RelativeSource Mode=TemplatedParent}, Path=FontSize, but it also cannot solve the problem. Why is this situation occurred? How can I make the the exclamation mark gets the same size as TextBox?


Solution

  • Why don't you bind to the AdornedElementPlaceholder?

    <Style TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
    <Setter Property="Validation.ErrorTemplate">
        <Setter.Value>
            <ControlTemplate>
                <DockPanel LastChildFill="True">
                    <TextBlock Text="!" DockPanel.Dock="Right" 
                               FontSize="{Binding ElementName=adornerPlaceholder, Path=AdornedElement.FontSize}" 
                               Foreground="Red"/>
                    <AdornedElementPlaceholder  Name="adornerPlaceholder" />
                </DockPanel>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    </Style>
    

    This is untested, but it should work :)