How to access the tbRegistrationBtn.text property from code behind from a custom made style?
My button is being created dynamically from codebehind and gets added to the parent control (stackpanel):
The button gets created when i press a other button on my screen.
Codebehind:
Button newBtn = new Button();
newBtn.Width = 160;
newBtn.Height = 46;
newBtn.Style = this.FindResource("ButtonStyleRegistration") as Style;
spHorizontal.Children.Add(newBtn);
Xaml:
<Style x:Key="ButtonStyleRegistration" TargetType="{x:Type Button}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Grid x:Name="registrationButton">
<Rectangle Fill="#FF89959A" Height="Auto" RadiusY="15" RadiusX="15" Stroke="White" Width="Auto"/>
<TextBlock x:Name="tbRegistrationBtn" TextWrapping="Wrap" Text="" HorizontalAlignment="Center" Margin="7.5,14.973,0,16.84" d:LayoutOverrides="Height"/>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsFocused" Value="True"/>
<Trigger Property="IsDefaulted" Value="True"/>
<Trigger Property="IsMouseOver" Value="True"/>
<Trigger Property="IsPressed" Value="True"/>
<Trigger Property="IsEnabled" Value="False"/>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
<Setter Property="FontSize" Value="10.667"/>
</Style>
Any attempt to retrieve the textblock results in a null error.
Attempt:
Style style = this.FindResource("ButtonStyleRegistration") as Style;
newBtn.Style = style;
TextBlock tb = (TextBlock)style.Resources.FindName("tbRegistrationBtn");
tb.Text = "test";
Best regards.
You can use VisualTreeHelper to navigate though visual tree of your button. Use this helper function:
Also you need to force your button to build it’s visual tree based on template (because it is delayed by default):
And finally set your
TextBlocktext: