【发布时间】: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 默认控制样式造成的。您能否将信息发布为答案,以便我接受。