【问题标题】:Workaround for FontSize not getting inherited in Contentpresenter and ContentControl在 Contentpresenter 和 ContentControl 中未继承 FontSize 的解决方法
【发布时间】:2015-11-14 05:12:05
【问题描述】:

试图制作可以承载其他控件的 UserControl。以下是相关代码。

<UserControl … … … … >
  <Grid DataContext="{Binding RelativeSource={RelativeSource 
            Mode=FindAncestor, AncestorType={x:Type UserControl}}}">
      … … …
     <ContentPresenter Content="{Binding SomeContent}"/>
      … … …
  </Grid>
</UserControl>

如下使用这个 UserControl -

<myCtrl:ContainerUserControl FontSize="18pt">
    <myCtrl:ContainerUserControl.SomeContent>
        <Grid>
            <TextBox Text="Hello World"/>
        </Grid>
    </myCtrl:ContainerUserControl.SomeContent>
</myCtrl:ContainerUserControl >

问题是 FontSize 没有继承到 TextBox。我可以将 FontSize 设置为 TextBox,但这不是一个优雅的解决方案。我试过使用 ContentControl 但没有改变。也试过用

<ContentPresenter TextElement.FontSize="{Binding FontSize}" Content="{Binding SomeContent}"/>

也不行。 FontSize 并不是我唯一担心的事情。我可能还需要其他可继承的属性。

有什么办法可以解决这个问题?

【问题讨论】:

  • 给定的 xaml 应该可以正常工作。您可能在某处有一个默认的TextBox 样式来设置字体大小。请参阅Dependency Property Value Precedence - 本地值优先于样式设置器(因此在TextBox 上设置字体大小直接有效),而样式设置器优先于“继承”值(这就是为什么在UserControl 上设置字体大小或ContentPresenter 不起作用 - 假设这里确实有一个默认样式)。
  • @PieterWitvoet 谢谢。你说的对。问题是由于 Mahapps.Metro 默认控制样式造成的。您能否将信息发布为答案,以便我接受。

标签: wpf xaml


【解决方案1】:

给定的 xaml 应该可以正常工作。您可能在某处设置了字体大小的默认 TextBox 样式。请参阅Dependency Property Value Precedence - 本地值优先于样式设置器(因此直接在 TextBox 上设置字体大小有效),而样式设置器优先于“继承”值(这就是为什么在 UserControl 或 ContentPresenter 上设置字体大小不” t 工作 - 假设这里确实有一个默认样式在工作)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多