0

We have a style defined as follow:

<Style x:Key="StartButtonStyle" TargetType="{x:Type Button}">           
 <Setter Property="Template">
   <Setter.Value>
     <ControlTemplate>
       <Button ... Style="{StaticResource StartBtnStyle}">
         <Button.Content>
          <StackPanel>
              <TextBlock x:Name="Line1" Text="..." FontSize="20" />
              <TextBlock x:Name="Line2" Text="..." FontSize="8" />
          </StackPanel>
       </Button.Content>
    </Button>
   </ControlTemplate>
  </Setter.Value>           
 </Setter>      

We creates a button dynamically:

var button = new Button() {
    Margin = new Thickness(3d,3d,3d,10d),
    Style = FindResource("StartButtonStyle") as Style,
};

We want to find the "Line1" textblock inside the new button, and set the Text property:

var line1 = (TextBlock)button.FindName("Line1");

But it finds only "null" :( How should we find the textblock inside the button? Any advice is appreciated! Thanks in advance!

Zoltan Hernyak
  • 989
  • 1
  • 14
  • 35
  • Have a look at this thread https://stackoverflow.com/questions/636383/how-can-i-find-wpf-controls-by-name-or-type You should examine UI elements tree, `FindName` returns null, because it's located inside stackpanel – Pavel Anikhouski Jun 12 '19 at 08:10
  • You mean the "FindName" is not a recursive function? Hm :( It this special case can I give name to stackpanel, find it by name, then inside that find the Line1? I should try it... – Zoltan Hernyak Jun 12 '19 at 09:34

1 Answers1

1

Wait until the Style has been applied - there is no TextBlock elment before this - to the Button and then find the TextBlock in the visual tree:

var button = new Button()
{
    Margin = new Thickness(3d, 3d, 3d, 10d),
    Style = FindResource("StartButtonStyle") as Style,
};
button.Loaded += (s, e) => 
{
    TextBlock line1 = FindChild<TextBlock>(button, "Line1");
    if(line1 != null)
    {
        line1.Text = "...";
    }
};

The recursive FindChild<T> method is from here.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • I thought (for a short but happy moment) that UpdateLayout() should be enough - but it wasn't. :( But your solution works!! Thanks! – Zoltan Hernyak Jun 13 '19 at 06:50