How to change the font size of all(n number of ) texblocks inside the stack panel programmatically?
Asked Answered
T

4

6

I am creating 'n' number of textblocks inside a stack panel programmatically. I need to change change the font size(both increase and decrease of font size) of 'n' textblocks. Is it possible to change font size of all child's of stack panel in single statement? If not possible how it can be solved efficiently ?

Tanishatanitansy answered 4/3, 2013 at 7:6 Comment(1)
If you're creating the TextBlocks pragmatically, can't you set the FontSize from code when you're creating them? You might want to show some code, because it's not obvious why you'd have this problem.Manna
T
4

Yes, You can refer the code snippet below, where 'foobar' refers to your Stackpanel's Name.

        foreach (var children in foobar.Children)
        {
            (children as TextBlock).FontSize = 20;
        }
Tade answered 4/3, 2013 at 7:14 Comment(1)
you're asking for nullRef exceptions with this code.Latinalatinate
M
12

You can apply a style in markup:

<StackPanel.Resources>
<Style TargetType="TextBlock">
  <Setter Property="FontSize" Value="20"/>
</Style>
</StackPanel.Resources>
Marks answered 4/3, 2013 at 9:15 Comment(0)
T
4

Yes, You can refer the code snippet below, where 'foobar' refers to your Stackpanel's Name.

        foreach (var children in foobar.Children)
        {
            (children as TextBlock).FontSize = 20;
        }
Tade answered 4/3, 2013 at 7:14 Comment(1)
you're asking for nullRef exceptions with this code.Latinalatinate
S
2

If you want all Subelements another Style why not use "ContentControl"?

For example like this:

    <GroupBox Header="Some Header" FontSize="18" FontWeight="Bold">
        <ContentControl FontSize="14" FontWeight="Normal">
        ....
        </ContentControl
    <GroupBox>

All elements inside the ContentControl Block will be st with normal weight and a size of 14.
Stovall answered 23/9, 2019 at 5:34 Comment(0)
T
1

You can use styles to apply a value to a property for all TextBlocks inside the StackPanel.

Sorry for the previouse wrong answer.

Turaco answered 4/3, 2013 at 7:24 Comment(3)
For some reason none of the two methods you mentioned work on Windows Phone: TextBlock doesn't have a SetFontSize() method and trying to set TextBlock.FontSize on the stack panel, the way you can do it with plain WPF, doesn't work.Manna
@CosminPrund Are you using Silverlight in Windows Phone 7? Or something else?Turaco
I did File -> New -> Project -> Windows Phone -> Windows Phone App from Visual Studio 2012, whatever that defaults to.Manna

© 2022 - 2024 — McMap. All rights reserved.