试图创建一个可承载其他控件的用户控件。以下是相关代码。
问题在于FontSize属性不能被TextBox继承。我可以将FontSize设置为TextBox,但这并不是一个优雅的解决方案。我尝试使用ContentControl,但没有改变。也尝试使用。
<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}"/>
效果不佳。我担心的不仅仅是字体大小,可能还需要其他可继承的属性。
如何解决这个问题?
TextBox
样式,它设置了字体大小。请参见Dependency Property Value Precedence - 本地值优先于样式设置器(因此直接在TextBox
上设置字体大小有效),而样式设置器优先于“继承”的值(这就是为什么在UserControl
或ContentPresenter
上设置字体大小不起作用的原因-假设确实存在默认样式)。 - Pieter Witvoet