开发者

WPF scrollviewer - Access using multiple threads

I want to access a scrollviewer from another thread. Please tell me how to do detach it from the Main Thread so that I can change the Offsets of the scrollvi开发者_如何学运维ewer. Thanks


You can better search SO for related questions.

Anyways the answer is here.

if (myScrollviewer.InvokeRequired) 
{ 
    myScrollviewer.BeginInvoke(new MethodInvoker(delegate { //access your myScrollviewer here } )); 
}

or you can achieve this using dispatcher

Dispatcher UIDispatcher = Dispatcher.CurrentDispatcher;  // Use this code in the UI thread

and access your myScrollviewer using the UIDispatcher object created

UIDispatcher.Invoke(DispatcherPriority.Normal, new Action(() =>  
{  
    // access your myScrollviewer here 
}));  


WPF UIs have "thread affinity" - only the thread that creates the UI can update it.

For the above scenario, you'd have to cache the Dispatcher object (Dispatcher.CurrentDispatcher) when the UI is created. The other threads would have to delegate their code blocks to this object via an Invoke/BeginInvoke.. See this link


Controls can only be updated from the thread that created them. Look into the BackgroundWorker class if you need to execute a time consuming operation in another thread.


Another way aside from using the dispatcher is to use data binding. You can bind the dependency properties like HorizontalOffset to some property of an object that you can easily access in a different thread

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜