Lima
Lima

Reputation: 1211

Hide dynamically created child elements of a grid

I have a grid in which I have created and added elements from the code behind.

Dim staffImgLeft As New Controls.Image()
staffImgLeft.Name = "StaffImgLeft"
mainGrid.Children.Add(staffImgLeft)

When I am attempt to remove the child elements from the grid they are not being removed.

mainGrid.Children.Remove(mainGrid.FindName("StaffImgLeft"))

There are no errors when the code runs. Can anyone advise why my code isnt working?

Upvotes: 0

Views: 891

Answers (2)

Fraser
Fraser

Reputation: 17039

You should use RegisterName and UnregisterName so you have an accessor that simplifies access to the NameScope registration.

Dim staffImgLeft As New Controls.Image();
staffImgLeft.Name = "StaffImgLeft";
mainGrid.Children.Add(staffImgLeft);
// register name
mainGrid.RegisterName(staffImgLeft.Name, StaffImgLeft);

// then remove
mainGrid.Children.Remove(mainGrid.FindName("StaffImgLeft"));
// un-register if you intend to re-register an element with the same name later.
mainGrid.UnregisterName("StaffImgLeft");

You should probably read about WPF XAML Namescopes http://msdn.microsoft.com/en-us/library/ms746659.aspx

Upvotes: 1

brunnerh
brunnerh

Reputation: 184386

FindName returns null, hence nothing gets removed.

Register the name instead of setting it to make it findable:

mainGrid.RegisterName("StaffImgLeft",staffImgLeft)

Upvotes: 1

Related Questions