Reputation: 147
I have grid with 10 rows and 3 columns and I want to add TextBlock on that grid. When User clicks the horizontal button then text block should add in horizontal grid cell and if clicks on vertical button then add in vertical grid cell. on one click one textblock will be added. following is my code:
<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);
}
Upvotes: 2
Views: 847
Reputation: 274
You need to specify which Row
the TextBox
is going on.
newTextBox.SetValue(Grid.RowProperty, number);
Upvotes: 1
Reputation: 17392
Is to to create a list? if so, there are already built in controls within WPF that support this (no need to re-invent).
Example
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);
}
Though, handling events like this is a bit more 'Winform-ish'. With WPF, you would want to use MVVM, and handle the adding/updating of collections via a ViewModel (rather than code behind). Please look into MVVM once you have gained more experience with WPF.
For reference, see: How can I add items from a listbox to a list by clicking a button without any codebehind?
Upvotes: 0