Marvin's Blog【程式人生】

Ability will never catch up with the demand for it

10 Aug 2020

XAML的ContentPresente

ContentPresenter继承自FrameworkElement,可以用来显示ContentControl的内容。也可以用来显示非XAML control的内容。

ContentPresenter的派生类也不多,包括:

  • ScrollContentPresenter
  • GridViewItemPresenter
  • ListViewItemPresenter

ContentPresenter的一个用法是在ContentControl的ControlTemplate里面显示Content和ContentTemplate。听着可能有点绕,下面是一个简化的例子:

    <!-- Default style for Windows.UI.Xaml.Controls.Primitives.HyperlinkButton -->
    <Style TargetType="HyperlinkButton">
...
        <Setter Property="HorizontalAlignment" Value="Left"/>
        <Setter Property="VerticalAlignment" Value="Center"/>
...
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="HyperlinkButton">
                    <Grid>
                        <Border x:Name="Border"
                                Background="{TemplateBinding Background}"
                                BorderBrush="{TemplateBinding BorderBrush}"
                                BorderThickness="{TemplateBinding BorderThickness}"
                                Margin="3">
                            <ContentPresenter x:Name="ContentPresenter"
                                              Content="{TemplateBinding Content}"
                                              ContentTransitions="{TemplateBinding ContentTransitions}"
                                              ContentTemplate="{TemplateBinding ContentTemplate}"
                                              HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                                              VerticalAlignment="{TemplateBinding VerticalContentAlignment}" 
                    />
                        </Border>
                        <!--focus visuals omitted-->
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
```xml

所以,ContentPresenter其实是为了给ContentControl的Content携带更多部属以供设置。这些部属跟文字的显示相关,跟TextElement 中的部属有点类似。

在ContentControl的ControlTemplate里面指定ContentPresenter的话,ContentPresenter会默认绑定到ContentControl的Content和ContentTempalte属性。

ContentPresenter还可以通过ContentTemplateSelector 部属来影响所应用的模板。比如Border相关的部属:

```xml
<ContentPresenter BorderBrush="Red" BorderThickness="2" CornerRadius="10" Padding="12"/>

(本篇完)

comments powered by Disqus