I have just finished spending 5 hours on a bug which lead me down many different paths to only find that ALL of them were wrong and there is some sort of threading issue when using RichTextBox in a XAML based Windows Phone application.
A little background. I have an application which shows IM messages and I noticed that when I would load the initial set of data everything appeared as expected, however when I would load more items into the list (older messages) the data seemed to be out of order. This was weird, but to make it more weird the order in which the data was being displayed in the UI was pattern-less and random which really, really pissed me off.
To try to isolate the issue I ran though an entire series of steps to try to isolate the issue. Theses steps are:
- Ensure my data was in fact being ordered as expected in my underlying ObservableCollection – IT WAS
- Make sure that the UX control’s ItemSource is also ordered correctly – IT WAS
- Remove the use of my custom control which is displaying my data and replace it w/ a simple text box to make sure it was not a control issue – EVERYTHING WORKED AS EXPECTED (ordered correctly)
- Add back the custom UX control and put break points inside my dependency property to ensure my bindings were setup correctly – THEY WERE
*** At this point I am at my wits end so I go home for the day ***
- Add a text box along side w/ the existing RichTextBox and push the EXACT same value (e.NewValue.ToString()) into each and see what happens. The results are here:
As you can see my text box bindings/value are correct, but my RichTextBox data is completely wrong. It has the correct value ALONG with some data from another instance of this control… WTF
Now I get to thinking that this MUST be some sort of UX Threading issue. Just to see if I could solve this simply wrapped my entire call in a Dispatcher.BeginInvoke call, but of course this did not work.
I am now completely at my wits end, WTF do I do. The incoming bound value is correct but my control’s data is not… UGG
For fun I decided to CLEAR my RichTextBox’s contents (by using Blocks.Clear()) prior to setting it just to see what would happen and to my amazement EVERYTHING just worked as seen below.
Now I am 100% sure this is NOT the correct solution for this problem and I fully expect this to bit me in the A$$ at some point in the future, but I don’t care :) I have a significant demo in 1 day and I need to get stuff working ASAP.
Hope this helps.
Till next time
11-18-2013 6:10 AM