3

If I have a style that defines a control template, and in this I have a control, let's say a button, is there any way to access the button from code behind of the styled control?

Thank you guys! =)

Sergio
  • 2,078
  • 3
  • 24
  • 41

1 Answers1

9

Say you have a style defined as follows

        <Style x:Key="myStyle" TargetType="{x:Type Button}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Button x:Name="myTemplatedButton" Content="my templated button"/>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>

And you apply it to a button

<Button x:Name="myButton" Content="my default button"  Style="{StaticResource myStyle}"/>

You can access the button in the control template as follows

var myTemplatedButton = myButton.Template.LoadContent() as Button;

If the button is placed in a container inside the ControlTemplate, for example a StackPanel:

<StackPanel>
    <CheckBox IsChecked="True"/>
    <Button x:Name="myTemplatedButton" Content="my templated button"/>
</StackPanel>

You can extract the main container and use FindName method to get your templated button

var templatedControl = myButton.Template.LoadContent() as FrameworkElement;
var templatedButton = templatedControl.FindName("myTemplatedButton") as Button;

Hope this helps

Omri Btian
  • 6,499
  • 4
  • 39
  • 65
  • This doesn't work when that code is in the Generic.xaml file in the Themes folder. – petko_stankoski Jul 02 '14 at 09:28
  • @OmriBtian, LoadContent() create a new instance of object, when using 'Style' as 'ControlTemplate', use: 'myButton.Template.FindName("myTemplatedButton", myButton) as Button'. – antonio Mar 16 '23 at 04:58