ControlTemplate FindAncestor绑定无法正常工作

时间:2014-12-03 11:19:57

标签: wpf xaml binding controltemplate findancestor

我正在尝试在RichTextBox段落中嵌入Radio Buttons,但不应用单选按钮宽度和高度值:

<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>

嵌入代码就是这样:

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

1 个答案:

答案 0 :(得分:2)

段落元素实际上并不参与Visual Tree。所以Binding无法在树中找到Paragraph类型的元素。这就是绑定失败的原因。而不是Paragraph,另一个名为 ParagraphVisual 的控件用于代替Paragraph。您可以使用Snoop轻松找到它。

enter image description here

段落标记只是一个占位符来携带文本。 ParagraphVisual是用于绘制文本的内部类,因此您不能在XAML中使用该类型。

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