Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data Binding Value not updating from other thread

I have a WPF Application where I have the following StepCount Property in my ViewModel, which implements INotifyPropertyChanged, and then I have it bound to a TextBox in my View.

public int StepCount
{
   get { return _stepCount; } 
   set
   {
      _stepCount = value;
      OnPropertyChanged("StepCount");
   }
}

In the XAML, here is what the DataBinding looks like:

<TextBox Text="{Binding Path=StepCount}" />

This works great, and if I change the StepCount value, the Textbox value updates accordingly.

However, my issue is that I have another thread that is incrementing the StepCount, and in that case, the TextBox value is not updating. As soon as the thread ends, the Textbox value updates to the correct value.

I need the Textbox value to update everytime my other thread increments the StepCount. As it is right now, the Textbox value only shows an update after the thread finishes.

The other thread is incrementing StepCount, but the change is not being displayed in the UI until the thread ends.

Any ideas?

UPDATE

I appreciate all of the responses. This issue was puzzling because code that was previously working seemed to quit working, as was the case with these particular bindings.

When I installed VS 2011 Beta, it installs the .NET 4.5 Beta Framework, and when I uninstalled VS 2011 Beta under the suspicion that it may be causing problems, it did not uninstall the .NET 4.5 Beta Framework.

I just now uninstalled the .NET 4.5 framework and did a repair install of the .NET 4.0 framework. After completing those steps, my data bindings worked correctly, and now Textbox is correctly updating whenever another thread increments StepCount.

So, it appears, the .NET 4.5 Beta Framework may cause issues with data bindings.

I'll follow up with this by submitting an issue with Microsoft.

Thanks everyone for your responses.

like image 667
Nathan Dace Avatar asked Nov 04 '22 03:11

Nathan Dace


1 Answers

As you've discovered the WPF classes that you've bound your View to in the View model operate within the UI thread.

Ideally you should change the StepCount property of your view model using the WPF Dispatcher and the Invoke command. This will marshell the call appropriately.

See this article for more information on this process.

like image 179
ChrisBD Avatar answered Nov 30 '22 01:11

ChrisBD