Reputation: 37
I have a windows 8 app created in xml and using code-behind. I have a button that, when pressed, will create a canvas, and put a grid inside of it.
private void AddClass_Click_1(object sender, RoutedEventArgs e)
{
SolidColorBrush greenBrush = new SolidColorBrush(Windows.UI.Colors.Green);
Thickness size = new Thickness();
size.Top = 20;
size.Right = 20;
size.Left = 20;
size.Bottom = 20;
Canvas newcanvas = new Canvas();
newcanvas.Background = greenBrush;
newcanvas.Width=500;
newcanvas.Height=500;
newcanvas.Margin=size;
newcanvas.Name = "Class3";
GridView temp = new GridView();
newcanvas.Children.Add(temp);
classes.Items.Add(newcanvas);
}
What I need to now be able to do is, add MORE elements into the canvas I've just created, at any given time using a button, but I'm not sure how to reference this newly created canvas.
Upvotes: 1
Views: 4934
Reputation: 89285
Since you added newly created canvas this way :
classes.Items.Add(newcanvas);
Then I think, first thing to try to access it later is from Items
property of classes
:
classes.Items
If you have more then one object in Items
, just iterate through Items
and check if the item type is Canvas
.
Upvotes: 0
Reputation: 301
Simply move your Canvas declaration
Canvas newcanvas = new Canvas();
outside the function but within the scope you plan to address it from.
Later when you want to reference it again from the code behind on your button, it will still exist.
Upvotes: 0
Reputation: 11426
Save a ref at the class level:
Canvas myCanvas;
then create it only the first time:
private void AddClass_Click_1(object sender, RoutedEventArgs e)
{
if(myCanvas == null)
{
myCanvas = new Canvas();
newcanvas.Background = greenBrush;
newcanvas.Width=500;
newcanvas.Height=500;
newcanvas.Margin=size;
newcanvas.Name = "Class3";
}
GridView temp = new GridView();
newcanvas.Children.Add(temp);
classes.Items.Add(newcanvas);
}
But why not define you Canvas
in XAML? Then if you give it a name you can refer to in code-behind:
<Canvas Name="myCanvas" Width="500" ...>
</Canvas>
private void AddClass_Click_1(object sender, RoutedEventArgs e)
{
myCanvas.Children.Add(new GridView());
}
Upvotes: 1