我是C#的新手。我试图通过单击按钮将文本框添加到网格。单击此按钮时,网格上的所有内容都会消失:
private void addLine_Click(object sender, System.EventArgs e)
{
System.Windows.Controls.TextBox txt = new System.Windows.Controls.TextBox();
txt.Name = "textBox8";
dxfLines.Children.Add(txt);
}
这也是xaml:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DXFGenerator" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Name="dxfLines">
<TextBox Height="23" HorizontalAlignment="Left" Margin="271,94,0,0" Name="textBox1" VerticalAlignment="Top" Width="120" />
<Button Content="Generate DXF" Height="23" HorizontalAlignment="Left" Margin="286,194,0,0" Name="button1" VerticalAlignment="Top" Width="84" Click="button1_Click" />
<Button Content="Add Line" Height="23" HorizontalAlignment="Left" Margin="391,196,0,0" Name="button2" VerticalAlignment="Top" Width="75" Click="addLine_Click" />
</Grid>
</Window>
答案 0 :(得分:2)
如果您使用网格,则需要定义行和列,因为xaml应该看起来像这样:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="DXFGenerator" Height="350" Width="525" Loaded="Window_Loaded">
<Grid Name="dxfLines" x:FieldModifier="private" >
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<TextBox Height="23" HorizontalAlignment="Left" VerticalAlignment="Top" Width="120" Grid.Column="2" Grid.Row="4" />
<Button Content="Generate DXF" Height="23" HorizontalAlignment="Left" Grid.Column="1" Grid.Row="6" VerticalAlignment="Top" Width="84" Click="button1_Click" />
<Button Content="Add Line" Height="23" HorizontalAlignment="Left" Grid.Column="2" Grid.Row="6" VerticalAlignment="Top" Width="75" Click="addLine_Click" />
</Grid>
</Window>
您还需要为要添加的文本框指定行和列,以便gird知道文本框的放置位置。 addLine click的内容应如下所示:
System.Windows.Controls.TextBox txt = new System.Windows.Controls.TextBox();
txt.Name = "textBox8";
Grid.SetColumn(txt,1);
Grid.SetRow(txt, 1);
dxfLines.Children.Add(txt);