<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>
{
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);
}
privatevoid btnClick_Click(object sender, RoutedEventArgs e)
{
Border border;
TextBox tb;
for (int i =0; i < Grid1.RowDefinitions.Count; i++)
{
// 這個方法是循環(huán)Grid下所有控件的方法
//FindName 方法只能查詢在XAML中定義的組件,后臺動態(tài)添加的需要手動寫循環(huán)來處理
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) +"行的摘要不能為空");
}
}
}
}
}
}
如果是在xaml中添加,,應用FindName
本文來自lilipangtou的博客,原文地址:http://hi.baidu.com/lilipangtou/blog/item/0e2653ccf0dd8a21f8dc6131.html