来自代码的风格的访问控制 [英] Access control in style from code

查看:76
本文介绍了来自代码的风格的访问控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有一个定义控件模板的样式,并且我有一个控件(比如一个按钮),有什么办法可以从样式化控件后面的代码中访问该按钮?

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?

谢谢你们! =)

推荐答案

假设您的样式定义如下

        <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>

然后将其应用于按钮

<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;

如果按钮放置在ControlTemplate内的容器中,例如StackPanel:

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>

您可以提取主容器并使用 FindName 获取模板按钮的方法

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;

希望这会有所帮助

这篇关于来自代码的风格的访问控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆