ControlTemplate FindAncestor binding not working

815 views Asked by At

I'm trying to embed RadioButtons in RichTextBox Paragraphs, but RadioButton Width and Height values are not applied:

<Style x:Key="styleRb" TargetType="{x:Type RadioButton}">
    <Setter Property="Focusable" Value="False"></Setter>
    <Setter Property="Margin" Value="3,0,3,-1"></Setter>
    <Setter Property="Padding" Value="0,0,0,0"></Setter>
    <Setter Property="HorizontalAlignment" Value="Center"></Setter>
    <Setter Property="VerticalAlignment" Value="Center"></Setter>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type RadioButton}">
                <BulletDecorator Background="Transparent">
                    <BulletDecorator.Bullet>
                        <!--Values are applied:-->
                        <!--<Grid Width="13" Height="13">-->
                        <!--Values are not applied:-->
                        <Grid Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Paragraph}}, 
                                              Path=FontSize}"
                              Height="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Paragraph}}, 
                                               Path=FontSize}">
                            <Ellipse Stroke="Black" StrokeThickness="2.0"
                                     Fill="Gold" Opacity="1.0">
                            </Ellipse>
                        </Grid>
                    </BulletDecorator.Bullet>
                </BulletDecorator>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

Embed-Code is this:

RadioButton rb = new RadioButton();
rb.Style = (Style)Application.Current.FindResource("styleRb");
InlineUIContainer container = new InlineUIContainer(rb, rtbInsertionPosition);
1

There are 1 answers

1
Jawahar On

Paragraph elements are not actually participate in Visual Tree. So Binding cannot find an element of type Paragraph in the tree. That is the reason the binding fails. Instead of Paragraph, another control called ParagraphVisual used to render in place of Paragraph. You can easily find this using Snoop.

enter image description here

Paragraph tag is just a placeholder to carry the text. ParagraphVisual is an internal class used to draw text, so you cannot use that type in XAML.

http://referencesource.microsoft.com/#PresentationFramework/Framework/MS/Internal/PtsHost/ParagraphVisual.cs