I am trying to make a warning window in an application. The window needs to run on a seperate thread and contains among other things a Canvas depicting a failing object. The Canvas already exists in the main application, and what i need is simply to show the same Canvas in the warning window. The problem is that i get an error saying that another thread owns the object. I tried doing a deep copy using this method but with no luck. Is there anything i missed, or is there really no simple method to copy a Canvas, or a collection of images. Alternatively, would it be possible to do the deep copy and then change the treading affinity of the copied object?
I should think that someone has encountered this problem before, but my serching skills have given me no relevant results this time.
Thanks in advance! -ruNury
EDIT 1
private Canvas cloneCanvas()
{
Canvas testcanv = new Canvas();
Dispatcher.Invoke(new Action(delegate
{
var t = SomeViewModel.GetCanvasWithImages();
testcanv = CopyCanvas(t);
}));
return testcanv;
}
public static UIElement DeepCopy(UIElement element)
{
if (element != null)
{
var xaml = XamlWriter.Save(element);
var xamlString = new StringReader(xaml);
var xmlTextReader = new XmlTextReader(xamlString);
var deepCopyObject = (UIElement)XamlReader.Load(xmlTextReader);
return deepCopyObject;
}
return null;
}
private Canvas CopyCanvas(Canvas inputCanvas)
{
if (inputCanvas != null)
{
var outputCanvas = new Canvas();
foreach (UIElement child in inputCanvas.Children)
{
outputCanvas.Children.Add(DeepCopy(child));
}
return outputCanvas;
}
return null;
}