locked
how can I get textblock fontweight , fontcolor RRS feed

  • Question

  • Guys,

    Does anyone know how to get fontweight , fontcolor from specific words of a textblock in c#, as those code below, how can I get those run elements

    <TextBlock FontSize="20" x:Name="boardField" Margin="34,40,30,31" TextWrapping="Wrap" Foreground="White" FontWeight="ExtraBlack" FontFamily="Kristen ITC">
          <Run FontWeight="Normal" Text=" this is my "/>
          <Run FontWeight="Bold"  Text="blackboard"/>
      </TextBlock>

    many thx

    Wednesday, November 4, 2009 1:06 PM

Answers

  •  You can either name the run elements and access them in code behind i.e.

     

    <TextBlock FontSize="20" x:Name="boardField" Margin="34,40,30,31" TextWrapping="Wrap" Foreground="White" FontWeight="ExtraBlack" FontFamily="Kristen ITC">
      <Run x:Name="runNormal" FontWeight="Normal" Text=" this is my "/>
      <Run x:Name="runBold" FontWeight="Bold"  Text="blackboard"/>
    </TextBlock>
    CodeBehind:
    FontWeight fontWeight = runNormal.FontWeight;

    Or you could use the VisualTreeHelper and interrogate the content of the TextBlock.

    Edit: How could I forget about Inline?

    Wednesday, November 4, 2009 3:28 PM
  • Access Run element by calling TextBlock.Inlines collection:

     foreach (Inline l in boardField.Inlines)
                {
                  Run r = l as Run;
                  if(r != null)
                    MessageBox.Show(r.FontWeight.ToString() + ": " + r.Text);
                }

    Wednesday, November 4, 2009 3:40 PM

All replies

  •  You can either name the run elements and access them in code behind i.e.

     

    <TextBlock FontSize="20" x:Name="boardField" Margin="34,40,30,31" TextWrapping="Wrap" Foreground="White" FontWeight="ExtraBlack" FontFamily="Kristen ITC">
      <Run x:Name="runNormal" FontWeight="Normal" Text=" this is my "/>
      <Run x:Name="runBold" FontWeight="Bold"  Text="blackboard"/>
    </TextBlock>
    CodeBehind:
    FontWeight fontWeight = runNormal.FontWeight;

    Or you could use the VisualTreeHelper and interrogate the content of the TextBlock.

    Edit: How could I forget about Inline?

    Wednesday, November 4, 2009 3:28 PM
  • Access Run element by calling TextBlock.Inlines collection:

     foreach (Inline l in boardField.Inlines)
                {
                  Run r = l as Run;
                  if(r != null)
                    MessageBox.Show(r.FontWeight.ToString() + ": " + r.Text);
                }

    Wednesday, November 4, 2009 3:40 PM
  • thanks guys

    Wednesday, November 4, 2009 5:33 PM