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!

2
  • Have a look at this thread stackoverflow.com/questions/636383/… You should examine UI elements tree, FindName returns null, because it's located inside stackpanel Commented Jun 12, 2019 at 8: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... Commented Jun 12, 2019 at 9:34

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I thought (for a short but happy moment) that UpdateLayout() should be enough - but it wasn't. :( But your solution works!! Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.