Removing specific object from a container and add it to another
-
I figured out how to see if an object within a container is a specific object, but how to translate it to another container? The following doesn' t work.
foreach (UIElement el in LayoutRoot.Children)
{
if (el is Button)
{
LayoutRoot.Children.Remove(el);
StackPanel1.Children.Add(el);
}
} -
I figured out how to see if an object within a container is a specific object, but how to translate it to another container? The following doesn' t work.
foreach (UIElement el in LayoutRoot.Children)
{
if (el is Button)
{
LayoutRoot.Children.Remove(el);
StackPanel1.Children.Add(el);
}
}As per my understadning, it is containing reference of button so it may be the cause. Try with following DeepCopy approach:
foreach (UIElement el in LayoutRoot.Children)
{
if (el is Button)
{
string shapestring = XamlWriter.Save(el);
StringReader stringReader = new StringReader(shapestring);
XmlTextReader xmlTextReader = new XmlTextReader(stringReader);
UIElement DeepCopyobject = (UIElement)XamlReader.Load(xmlTextReader);
StackPanel1.Children.Add(DeepCopyobject);
LayoutRoot.Children.Remove(el);
}
}If it is not working or if you have any other approach then please let me know. Thanks,
Parwej Ahamad ahamad.parwej@gmail.com
-
I figured out how to see if an object within a container is a specific object, but how to translate it to another container? The following doesn' t work.
foreach (UIElement el in LayoutRoot.Children)
{
if (el is Button)
{
LayoutRoot.Children.Remove(el);
StackPanel1.Children.Add(el);
}
}If you run that code in debug mode you WILL experience an exception. You cannot remove an item from a collection that is being enumerated. So what I do in that case is this:
List<int> itemsToRemove = new List<int>(); for ( int index = 0; index<LayoutRood.Children.Count; index++ ) { if ( LayoutRoot.Children\[index\] is Button ) itemsToRemove.Add(index); } // Next process the items to move foreach ( int element in itemsToRemove ) { Button oldElement = LayoutRoot.Children\[element\] as Button; LayoutRood.Children.RemoveAt(element); StackPanel1.Children.Add(oldElement); }
Take this one warning into account: you MIGHT get an exception that the element is already a member of another collection. The exception will point at your StackPanel1 add to the elements. If that happens then do the following:
Button newElement = new Button; newElement.Name = oldElement.Name; . . . // you get the idea // now add the new instance of the button to the collection