首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 媒体动画 > CAD教程 >

WPF 如其遍历Grid中所有控件?

2013-01-11 
WPF 如果遍历Grid中所有控件??WPF 如果遍历Grid中所有控件?? [解决办法]GridGrid.RowDefinitionsRowD

WPF 如果遍历Grid中所有控件??
WPF 如果遍历Grid中所有控件?? 
[解决办法]

    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="100" />
            <RowDefinition Height="35"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
        </Grid.ColumnDefinitions>
        <Button x:Name="btnClick" Margin="50,0,50,0" Grid.Row="1" Grid.Column="0" Content="Click Me" Click="btnClick_Click" />
        <Grid Grid.Row="0" Grid.Column="0" x:Name="Grid1">
        </Grid>
    </Grid>


public Window1()
        {
            InitializeComponent();
            this.Loaded += new RoutedEventHandler(Window1_Loaded);
        }

        void Window1_Loaded(object sender, RoutedEventArgs e)
        {
            RowDefinition rd = new RowDefinition();
            Grid1.RowDefinitions.Add(rd);
            //添加第0列
            Border b = new Border();
            b.BorderThickness = new Thickness(0, 0, 1, 1);
            b.BorderBrush = Brushes.Black;
            b.Name = "Border_" + (Grid1.RowDefinitions.Count - 1) + "_0";

            TextBox tb = new TextBox();
            string x = "TB_" + (Grid1.RowDefinitions.Count - 1) + "_0";
            tb.Name = "TB_" + (Grid1.RowDefinitions.Count - 1) + "_0";
            tb.BorderThickness = new Thickness(0);
            tb.ToolTip = tb.Name;
            b.Child = tb;//
            b.SetValue(Grid.RowProperty, Grid1.RowDefinitions.Count - 1);
            b.SetValue(Grid.ColumnProperty, 0);
            Grid1.Children.Add(b);

        }

        private void btnClick_Click(object sender, RoutedEventArgs e)


        {
            Border border;
            TextBox tb;
            for (int i = 0; i < Grid1.RowDefinitions.Count; i++)
            {
                // 这个方法是循环Grid下所有控件的方法
                //FindName 方法只能查询在XAML中定义的组件,后台动态添加的需要手动写循环来处理
                for (int j = 0; j < Grid1.Children.Count; j++)
                {
                    border = Grid1.Children[i] as Border;
                    if (border != null && border.Name == "Border_" + i + "_0")
                    {
                        tb = border.Child as TextBox;
                        if (tb != null && tb.Name == "TB_" + i + "_0")
                        {
                            if (tb.Text.Trim().Equals(""))
                            {
                                MessageBox.Show("第" + (i + 1) + "行的摘要不能为空");
                            }

                        }
                    }
                }
            }
        }

热点排行