I have created a small chatting application in C#, and started as a Console Application. However I want to create a GUI for it using WPF. It’s a class named DanMessengerClientwith functions such as InitializeConnection(), SendMessage(string msg), etc.
I have already designed the UI in Visual Studio, and it created it’s Window1 class on Window1.xaml.cs by default. I created an event handler for the “Send” button that only appends some dummy text to a textarea as of now. My question is, how should I call the SendMessage() function from the WIndow1 class?
I tried creating the object in that class, but since I also need to access the Textbox from inside the first class (i.e. When I recieve a message, update the textbox), adding the reference to the Window1 class throws a StackOverflow exception because it keeps creating references in an infinite loop.
I’m new to GUI applications. How should I proceed?
The canonical way in WPF to display data is to bind a control to it (see Data Binding in MSDN). This would probably require that you wrap or refactor your messenger class so that it exposes bindable properties. For example, your messenger class might expose a property called MessageText, which you update every time you receive a message:
Now you would bind the TextBox.Text property to this new property:
This assumes that the messenger object is set as the window’s DataContext, e.g. when the window creates the messenger:
Note your messenger class must implement INotifyPropertyChanged for this to work. Also note the OneWay binding so that if the user edits the TextBox it doesn’t muck up the MessageText property. (You could also use a TextBlock, so that the user couldn’t edit it at all.)
When you’ve got this set up, WPF will automatically monitor for changes in the _myMessenger.MessageText property, and update the TextBox.Text as they happen (i.e. as messages are received).
Finally, regarding how to do the send: just pass the text:
Use the Name attribute to name the text box containing the message to be sent: