Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Workaround for FontSize not getting inherited in Contentpresenter and ContentControl

Tags:

wpf

xaml

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>

And using this UserControl as below -

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

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}"/>

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?

like image 222
Amit Hasan Avatar asked Sep 26 '22 05:09

Amit Hasan


1 Answers

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).

like image 60
Pieter Witvoet Avatar answered Sep 29 '22 07:09

Pieter Witvoet