日期:2014-05-17  浏览次数:20928 次

WPF,获取窗体中的元素,哪里出错了?

<Window.Resources>
    <Style TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Border Name="border1">
                        <ContentPresenter />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Border Name="border2">
    <Grid Name="grid1" HorizontalAlignment="Left" Width="596">     
        <Border Name="border3" />     
        <Button x:Name="button1" Content="Button" Click="Button_Click" Margin="217,303,258,155"/>   
    </Grid>
</Border>



private void Button_Click(object sender, RoutedEventArgs e)
{
    var count = VisualTreeHelper.GetChildrenCount(this);
    if (count > 0)
    {
        for (var i = 0; i < count; i++)
        {
            var child = VisualTreeHelper.GetChild(this, i);
            var t = child as Border;
            if (t != null)
                MessageBox.Show(t.Name);
        }
    }
}


1:上面代码,获取窗口中的Border元素,为什么没有搜出来呢?只搜了一个Name为空字符串的Border。