views:

63

answers:

2

I have a window that contains a label (player1). I also have a class that gathers data asynchronously in the background inside a thread. When that data has been gathered, I want to changed the content of my label. Since the label was created by the UI and I'm trying to edit it from another thread, I tried using Dispatcher. However, after hours of trying and different examples, I can't get it to work. In it's most simple form below, the method dispatchP1 changes the value of player1 when called from my main window. However, it doesn't work when called from my class. Also, I don't receive an error or anything.

public delegate void MyDelegate();

public void dispatchP1()
 {
 player1.Dispatcher.BeginInvoke(new MyDelegate(p1SetContent));
 }

public void p1SetContent()
 {
 player1.Content = "text";
 }

Any help would be appreciated.

+1  A: 

That code doesn't seem particularly problematic - but WPF has a habit of swallowing exceptions. In your App.xaml, you can handle the event DispatcherUnhandledException and put a breakpoint in there to determine if it is really throwing an exception or not.

vcsjones
I added DispatcherUnhandledException to my App.xaml and specified a method to catch it, but I'm still not getting an error from that code.
Chris Hendry
I've literally copied and pasted your code into a sample project and it worked fine - you can download it here and try it out for yourself. http://bit.ly/d4pHvN
vcsjones
Your projects works, but when I call it from an inherited class it doesn't. The p1SetContent function is called, but the Content of player1 is never changed. If I check the property of player1.Content, it returns the updated value, but it is never reflected in the UI.
Chris Hendry
What is being inherited? MainWindow (in the case of my example)?
vcsjones
In the case of your example, MainWindow is being inherited by the separate class. Also, what version of VS are you using. I had a couple of errors when I tried to load your project, but your code works just fine.
Chris Hendry
That's because by inheriting, they have different dispatchers and different owners. You're setting the player1.Content on the inherited window, not the parent. That's why it appears to do nothing.
vcsjones
Thanks for your help, I figured it out. I made my class non-inherited, and then passed the parent window to the class constructor so I could reference the parent.
Chris Hendry
That'll do it, generally inheritance of windows only causes problems unless you are using it to actually display another window.
vcsjones
Yeah, I've discovered that. The inheritance wasn't actually necessary anyway.
Chris Hendry