wpfbindingrelativesource

Bind to ControlTemplate onwer's property


I have a ControlTemplate, which I use as Validation.ErrorTemplate:

            <ControlTemplate x:Key="ErrorTemplate">
                <Border BorderBrush="Red" BorderThickness="2">
                    <Grid>
                        <AdornedElementPlaceholder/>
                        <TextBlock Text="{Binding [0].ErrorContent}" HorizontalAlignment="Right" Margin="100 0 5 0" Foreground="Red" Width="{Binding RelativeSource={RelativeSource TemplatedParent}, Path=ActualWidth}" TextWrapping="Wrap"/>
                    </Grid>
                </Border>
            </ControlTemplate>

            <Style TargetType="TextBox" BasedOn="{StaticResource DefaultTextBoxStyle}">
                <Setter Property="TextAlignment" Value="Left"/>
                <Setter Property="MinHeight" Value="50"/>
                <Setter Property="Validation.ErrorTemplate" Value="{StaticResource ErrorTemplate}"/>
            </Style>

I am trying to bind ControlsTemplate's TextBlock's Width to ActualWidth of TextBlock using it by TemplatedParent, but it is not working properly.

Any ideas why?


Solution

  • You could bind to the ActualWidth of the AdornedElementPlaceholder:

    <Grid>
        <AdornedElementPlaceholder x:Name="elem"/>
        <TextBlock Text="{Binding [0].ErrorContent}" HorizontalAlignment="Right"
                   Foreground="Red" Width="{Binding Path=ActualWidth, ElementName=elem}" TextWrapping="Wrap"/>
    </Grid>