如何获取x:网格的名称?

时间:2015-01-02 11:00:45

标签: c# .net wpf

我想知道x:Grid子名称,如下例所示:

<Grid x:Name="one" Grid.Row="0"  Margin="49.667,15,15,15">
        <Grid x:Name="container1" Background="Red" Margin="10"/>
        </Grid>
    <Button Content="mov" Foreground="White" x:Name="first" HorizontalAlignment="Left" Margin="8,44.833,0,70.167" Width="29.334" Background="Black" Click="first_Click"/>

这里是我点击时的代码:

private void first_Click(object sender, System.Windows.RoutedEventArgs e)
    {

        var ttt = FindVisualChild<Grid>(one);
        MessageBox.Show(ttt.ToString());

    }

    private static T FindVisualChild<T>(DependencyObject parent) where T : DependencyObject
    {
        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
        {
            DependencyObject child = VisualTreeHelper.GetChild(parent, i);
            if (child != null && child is T)
                return (T)child;
            else
            {
                T childOfChild = FindVisualChild<T>(child);
                if (childOfChild != null)
                    return childOfChild;
            }
        }
        return null;
    }

当我点击该消息时,只显示此内容“System.Window.Controls.Grid”而不是我想知道x:名称在这种情况下“container1”然后我问你是否有任何建议,我可以收到x:网格的名称。

提前谢谢。

此致

1 个答案:

答案 0 :(得分:1)

信用证转到dkozl,为您提供OP评论中的答案。我想提供一些额外的信息来补充它。

在XAML中向您公开的任何元素都可以在代码隐藏中作为属性访问(有一些例外,但大多数情况下这都是真的)。​​

<Grid x:Name="one" Grid.Row="0"  Margin="49.667,15,15,15">
        <Grid x:Name="container1" Background="Red" Margin="10"/>
        </Grid>
    <Button Content="mov" Foreground="White" x:Name="first" HorizontalAlignment="Left" Margin="8,44.833,0,70.167" Width="29.334" Background="Black" Click="first_Click"/>

如果您愿意,可以访问网格属性,如

private void first_Click(object sender, System.Windows.RoutedEventArgs e)
{
    this.one.Background = Brushes.Yellow;
    this.one.Margin = new Thickness(0, 5, 10, 25);
}

您也不需要使用可视树查找,因为您已为网格提供了名称,前提是代码隐藏与保存两个网格的视图相关联。

你可以这样做:

private void first_Click(object sender, System.Windows.RoutedEventArgs e)
{
    MessageBox.Show(this.container1.Name);
}