✅ ERROR: The calling thread cannot access this object because a different thread owns it.
Hey, I'm getting this error
The calling thread cannot access this object because a different thread owns it.
from the following method when trying to add a Run
element to a RichTextBox
I've tried Googling a ton and even tried ChatGPT to see if it could fix it for me, all answers point to use chatRichTextBox.Dispatcher.Invoke
but it still fails, any ideas?
10 Replies
Instead of using a ricthtextbox, you could use a itemscontrol, u create a datatemplate add some scrolling
then you can use an ObservableCollection<Message>
and instead of all that u would just add items to the Observable collection and it would update your ui
This is just an idea:
And by adding items to:
It would populate the ItemsControl
https://wpf-tutorial.com/list-controls/itemscontrol/
That's an excellent example! Unfortunately it still gives me this error when I try to add the messages :(
Line:
ChatHistoryCollection.Add(new ChatMessage { UsernameColour= new SolidColorBrush(mediaColor), Username = username, Message = message });
Error:
System.NotSupportedException: 'This type of CollectionView does not support changes to its SourceCollection from a thread different from the Dispatcher thread.'
yes now u have to use the dispatcher
because you're calling it from a different thread
Am I doing something wrong in the MainWindow constructor?
Ah okay I'll give that a go first
Like this?
should work
ChatHistoryCollection is a public property right?
That worked! Not getting the colour I expected from the username though, that might be cause either converting it wrong or grabbing the wrong value from TwitchLib's
OnMessageReceivedArgs
yeah I wouldn't know about that
I never used that lib
and if u want the messages order to be inverted just change it to Insert(0, new ChatMessage.... instead of Add
then u avoid having to scroll
unless u want to see old messages
Amazing, thank you for the help :)
no worries, $close
If you have no further questions, please use /close to mark the forum thread as answered