Reputation: 49
I have Added buttons on my page in a canvas on the screen, so when I click 'Add Title' it will add a text box in a certain position and when I click Add Question it will do the same thing.
Here is the code I have which preforms this action.
public void AddTitle_Click(object sender, RoutedEventArgs e)
{
TextBox x = new TextBox();
x.Name = "new_textbox";
x.TextWrapping = TextWrapping.Wrap;
x.Height = 20;
x.Width = 100;
x.AcceptsReturn = true;
x.Margin = new Thickness(5, 10, 0, 0);
canvas1.Children.Add(x);
Canvas.SetLeft(x, 100);
Canvas.SetTop(x, 100);
}
private void AddQuestion_Click(object sender, RoutedEventArgs e)
{
TextBox x = new TextBox();
x.Name = "new_textbox";
x.TextWrapping = TextWrapping.Wrap;
x.Height = 20;
x.Width = 200;
x.AcceptsReturn = true;
x.Margin = new Thickness(5, 10, 0, 0);
canvas1.Children.Add(x);
Canvas.SetLeft(x, 140);
Canvas.SetTop(x, 140);
}
The Title position is the smaller Textbox and the question the bigger Textbox. A title can have any amount of questions it. So when I click 'Add question' I need it to appear below the last question Textbox and when I click add title I need it to appear below the last question but in a different position?
I deleted my old post as I figured out how to add the Textboxes.
Upvotes: 1
Views: 404
Reputation: 159
You don't have to add them like that.
You should use a TreeView or at least StackPanels and them add the items to them.
Also, this line:
x.Name = "new_textbox";
is not correct. If you add more than one element with the same name it will produce an error (it should be unique). You should leave that Property empty or give them names dynamically.
I hope you have enough info with this code approaches are multiple and quite longs.
EDIT: To locate a certain element in the window see this question: Get Absolute Position of element within the window in wpf
Upvotes: 2