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.Ad开发者_StackOverflow社区d(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?
FindName
returns null, hence nothing gets removed.
Register the name instead of setting it to make it findable:
mainGrid.RegisterName("StaffImgLeft",staffImgLeft)
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
精彩评论