我有10行3列的网格,我想在该网格上添加TextBlock。当用户单击水平按钮时,文本块应添加在水平网格单元格中,如果单击垂直按钮,则添加垂直网格单元格。只需点击一下,就会添加一个文本块。 以下是我的代码:
<Button Content="Add Hrzntly" Grid.Row="0" Grid.Column="1" Width="100" Height="30" Click="Button_Click"/>
<Button Content="Add Vrtcly" Grid.Row="1" Grid.Column="0" Width="100" Height="30" Click="Button_Click_1"/>
<Grid ShowGridLines="True" x:Name="gridChart" Grid.Row="1" Grid.Column="1">
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
</Grid>
private void Button_Click(object sender, RoutedEventArgs e)
{
var newTextBox = new TextBox();
newTextBox.Width = 100;
newTextBox.Height = 30;
newTextBox.Text = "FTB solutions";
// here set new textbox parameters
gridChart.Children.Add(newTextBox);
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var newTextBox = new TextBlock();
newTextBox.Width = 100;
newTextBox.Height = 30;
newTextBox.Text = "FTB solutions";
// here set new textbox parameters
gridChart.Children.Add(newTextBox);
}
答案 0 :(得分:1)
您需要指定Row
正在进行的TextBox
。
newTextBox.SetValue(Grid.RowProperty, number);
答案 1 :(得分:0)
是要创建一个列表?如果是这样,WPF中已经有内置控件支持这一点(无需重新发明)。
示例强>
XAML:
<ListBox x:Name="myListBox Width="200" Margin="10"/>
xaml.cs:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
var listBoxItem = new ListBoxItem();
listBoxItem.Content = "this is a new item";
myListBox.Items.Add(listBoxItem);
}
尽管如此,处理这样的事件有点'Winform-ish'。使用WPF,您可能希望使用MVVM,并通过ViewModel(而不是代码隐藏)处理集合的添加/更新。一旦您获得了WPF的更多经验,请查看MVVM。
供参考,请参阅:How can I add items from a listbox to a list by clicking a button without any codebehind?