【问题标题】:Style inside ContentPresenter is not applied未应用 ContentPresenter 中的样式
【发布时间】:2014-12-17 09:59:55
【问题描述】:

我有以下 xaml:

<DataGrid ItemsSource="{Binding}" AutoGenerateColumns="True">
    <DataGrid.CellStyle>
        <Style TargetType="{x:Type DataGridCell}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="DataGridCell">
                        <Grid>
                            <ContentPresenter Height="50">
                                <ContentPresenter.Resources>
                                    <Style TargetType="TextBlock">
                                        <Setter Property="Padding" Value="4"/>
                                    </Style>
                                </ContentPresenter.Resources>
                            </ContentPresenter>
                        </Grid>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </DataGrid.CellStyle>
</DataGrid>

事实证明,TextBlock 的默认填充为 2,0。
为什么没有应用样式?

编辑:我使用了这个解决方案(来自 here),它从自动生成的 TextBlock (Content.Text) 中获取文本并将其显示在另一个 TextBlock 中:

<ControlTemplate TargetType="{x:Type DataGridCell}">
    <Grid SnapsToDevicePixels="True">
        <TextBlock Text="{Binding RelativeSource={RelativeSource TemplatedParent}, 
                                  Path=Content.Text}" Padding="4"/>
    </Grid>
</ControlTemplate>

【问题讨论】:

  • 为什么不在单元格模板中放置一个实际的TextBlock,并将其Padding 设置为4?
  • 您的想法是渲染一个带有 ContainerViusal 的文本块,其中又包含一个 ContentPresenter:有点不寻常。此外,这个想法只有在我使用 Margin 而不是 Padding 时才有效。

标签: wpf contentpresenter


【解决方案1】:

如果元素从 Control 继承,并且 TextBlock 不是从 Control 继承,则将隐式样式应用于 模板 中的元素。

要了解更多信息,请阅读这篇文章: MSDN Blog

更新答案

@JustinXL 提到了这一点,在我窥探 DataGrid 之后,在这个 范围模板不应该丢失样式,我发现本地样式确实设置为 覆盖隐式样式的文本块(由 DataGrid 生成)。

【讨论】:

  • 这是不正确的。 TextBlock 可以使用隐式样式设置样式。
  • @JustinXL,正如我在数据模板中没有提到的那样。这种行为是设计使然。
  • 我找到的这个答案也说明了这一点:stackoverflow.com/a/2479695/440030
  • 我知道,但他的情况不同。他在ContentPresenter 中定义了隐式样式,这使得TextBlock 和隐式样式在同一范围内。我只能猜测还有其他东西(另一种名为TextBlock 样式)覆盖了隐式样式。
  • @JustinXL,你说得对,在这个范围内,模板不应该失去风格。我窥探 DataGrid,发现一个本地样式设置为 TextBlock(由 DataGrid 生成),它覆盖了隐式样式。感谢您的关注。
猜你喜欢
  • 2015-10-23
  • 1970-01-01
  • 2013-12-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-27
  • 1970-01-01
  • 2015-10-07
相关资源
最近更新 更多