Access control in style from code [duplicate]

感情迁移 提交于 2019-12-06 12:05:49

问题


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


回答1:


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



来源:https://stackoverflow.com/questions/19208964/access-control-in-style-from-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!