Frage

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! =)

War es hilfreich?

Lösung

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

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top