意思是只有在Button类里才能调用FindName

解决方案 »

  1.   

    只能在Button类里才能使用FindName找到元素。。你可以在OnApplyTemplate里面找到这个元素。然后通过public的方法把这个元素暴露出来 
      

  2.   

    感觉用VisualTreeHelper会更容易找到。
      

  3.   

    但是在自定义元素的类里面,也找不到啊。看示例:<ResourceDictionary
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:WPF6">
        <Style TargetType="{x:Type local:CustomControl1}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="{x:Type local:CustomControl1}">
                        <Border>
                            <ContentPresenter/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
            <Setter Property="ContentControl.ContentTemplate">
                <Setter.Value>
                    <DataTemplate>
                        <TextBlock Name="PART_TextBlock" Text="{Binding}"/>
                    </DataTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ResourceDictionary>
    public class CustomControl1 : ContentControl
    {
        static CustomControl1()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(CustomControl1), new FrameworkPropertyMetadata(typeof(CustomControl1)));
        }
        public override void OnApplyTemplate()
        {
            TextBlock textblock = this.ContentTemplate.FindName("PART_TextBlock", this) as TextBlock;
        }
    }
    <Window x:Class="WPF6.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:WPF6"
            Title="MainWindow" Height="350" Width="725" Background="#FF71AC55">
        <Grid Name="grid1">
            <local:CustomControl1/>
        </Grid>
    </Window>窗体启动后,还是报错:此操作仅在应用此模板的元素上有效。
      

  4.   

    http://technet.microsoft.com/zh-cn/magazine/system.windows.frameworktemplate.findname(VS.90).aspx查找由模板生成的元素的示例
    http://technet.microsoft.com/zh-cn/magazine/bb395202(VS.90).aspx