问题
Okay, before anyone starts up, let me be clear...
I'm using a custom control, in this case Telerik's RadPane. When you deserialize these panes they come in through a callback method, and thus, are ALL owned/deserialized by one thread, and they cannot be cloned or deep copied, etc. so there are some huge limitations I am trying to work with. This is bad because, I want to add content to each pane but want them all to work within the confines of their own UI thread. For example, I want to add a list to a pane and have it update with millions of records, etc. but if I update one pane, the UI thread will lock up for all panes.
I need to create the contents of this object in a different thread, but the problem is, when I try to set the content, the obvious issue is that the object is not owned by the same thread that owns my pane:
myRadPane.Content = myGrid;
myGrid is owned by a different thread than myRadPane, so it doesn't want to set the content. Is there any way around this problem in WPF or a way to allow one object to be "shared" across UI threads?
Edit: Please note, I am fully aware of how dispatchers work, and my application makes use of them whenever the main UI thread needs updating for one pane. However, in this case, even while using dispatchers as minimally as possible, the UI thread bogs down under heavy load.
回答1:
You CAN copy WPF controls.
Call this in your creater Thread:
public string CopyWPFControl<T>(T source)
{
string childXaml = XamlWriter.Save(source);
var stringReader = new StringReader(childXaml);
return stringReader.ToString();
}
Transfer your result to your Dispatcher / STA thread and call:
public T RecreateWPFControl<T>(string source)
{
var xmlReader = XmlReader.Create(source);
var clonedChild = (T)XamlReader.Load(xmlReader);
return clonedChild;
}
So create your object in a Diferent Thread, then copy the Control and all its Bindings ect and use the output to display.
imported this will only copy the XAML description.
来源:https://stackoverflow.com/questions/21882609/is-there-any-way-to-use-an-object-across-two-sta-threads-in-wpf