In my application, i am generating multiple buttons at run time and add it to grid as following
for (int i = 0; i < ListOfMainCategories.Count; i++)
{
clsMainCategory tempCat = (clsMainCategory)ListOfMainCategories[i];
ButtonMainMenuCat btn = CreateMainButton(tempCat.CatTitle, i);
btn.Margin = new Thickness(0, 1, 0, 1);
btn.TabIndex = TabIndexNo;
if (i == 0)
{
buttonHomeMenu = btn;
}
btn.AddHandler(ButtonMainMenuSubSubCat.GotKeyboardFocusEvent, new RoutedEventHandler(ButtonMainMenuGotFocus), handledEventsToo: false);
// stackTableViewMainMenu.Children.Add(btn);
Grid.SetRow(btn, 1);
Grid.SetColumn(btn, i + 1);
gridHeader.Children.Add(btn);
}
After on particular event I removed all of these buttons from Grid.
gridHeader.Children.RemoveRange(0, gridHeader.Children.Count);
Here i Think i also need to Remove or dispose or unload these button from Memory. So How can i do this task ? Please suggest
Yuo can’t dispose of the button in the classical sense as there is nothing to dispose. You are dealing with managed code here. The memory allocation will be cleared up by the garbage collector as long as there are no references. In the code above you are keeping a reference to the button through the routed event handler so call
btn.RemoveHandlerbefore you remove it from the Grid.You could take a look at MSDN guidance on the WeakEvent pattern here: http://msdn.microsoft.com/en-us/library/aa970850