question

StefanoMora-Newdep avatar image
0 Votes"
StefanoMora-Newdep asked TimonYang-MSFT commented

[c#] How to share communicating class between Window classes

Hello everyone,
my WPF application is build around 4 Window classes; every window is run by a ShowDialog() command.

The application needs to communicate with external machine via socket connection: this communication is developed in a class.
The communication can interact with each window, the active one, receiving events and sending some commands.

How can i implement this requirement?

My first idea is to instantiate the communication class on the first window and then passing it by reference to the other following windows: they can receive the class and could connect the event system to receive events and send some kind of command.

Any other way?
Thanks, regards

dotnet-csharp
· 2
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

It's not real clear how you've designed this application but it sounds like a job for events or delegates. The communication class is instantiated in a constructor. The on active window subscribes to communication events while the on non-active window unsubscribes to communication events.

See Events (WPF)


0 Votes 0 ·

@StefanoMora-Newdep
I agree with AgaveJoe's view that the use of delegation is a suitable method, and this method has a low degree of coupling.
This is an example, which should give you some ideas:
Using Delegates to Communication Between Windows Forms

0 Votes 0 ·

1 Answer

Bruce-SqlWork avatar image
0 Votes"
Bruce-SqlWork answered StefanoMora-Newdep edited

I would use the singleton pattern.

· 1
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

Thanks, in this way every window will instantiate the communication class (singleton), only the first one will really create the object, the following window will receive the already-instantiated object.
So I will not need to pass the instance to every window.
is it?

Thanks

0 Votes 0 ·