Zoltan Hernyak
Zoltan Hernyak

Reputation: 1239

WPF dynamically create button by style and set control elements inside

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!

Upvotes: 0

Views: 1405

Answers (1)

mm8
mm8

Reputation: 169200

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.

Upvotes: 1

Related Questions