本文介绍了FontSize 未在 Contentpresenter 和 ContentControl 中继承的解决方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图使 UserControl 可以承载其他控件.以下是相关代码.

Trying to make UserControl that can host other control. The following is the relevant code.

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

并使用此 UserControl 如下 -

And using this UserControl as below -

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

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

Problem is that FontSize is not inherited to the TextBox. I can set FontSize to the TextBox but that is not an elegant solution. I have tried using ContentControl but no change. Also tried to use

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

效果也不好.FontSize 并不是我唯一担心的事情.我可能还需要其他属性来继承.

Doesn’t work as well. FontSize is not the only thing I am worried about. I might need other property to be inheritable as well.

可以做些什么来解决这个问题?

What can be done to solve this problem?

推荐答案

给定的 xaml 应该可以正常工作.您可能在某处设置了字体大小的默认 TextBox 样式.请参阅依赖属性值优先级 - 本地值采用优先于样式设置器(因此在 TextBox 上设置字体大小直接有效),而样式设置器优先于继承"值(这就是为什么在 UserControl 或 ContentPresenter 上设置字体大小不起作用 - 假设确实存在默认值在这里工作的风格).

The given xaml should work fine. You probably have a default TextBox style somewhere that sets the font size. See Dependency Property Value Precedence - local values take precedence over style setters (so setting the font size on the TextBox directly works), while style setters take precedence over 'inherited' values (which is why setting the font size on the UserControl or ContentPresenter doesn't work - assuming there's indeed a default style at work here).

这篇关于FontSize 未在 Contentpresenter 和 ContentControl 中继承的解决方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:41