Notify Gui that the data class has changed

In C #: I have a data class that is shared between several gui classes. I would like all the gui classes that used it to be notified when some properties change so that they can update the GUI.

In several properties, I have added delegates that GUI classes can listen for updates. This seems to be normal.

The problem I have is that more and more properties will require GUI notification. When this happens, I will have to add more delegates. It also seems to add extra responsibility for the data class that it should manage.

Is there some general pattern that I can use to monitor this class to extract this notification responsibility from the data class?

+4
source share
5 answers

The general way to do this is to implement INotifyPropertyChanged for the data class.

EDIT: If you have many properties, this can lead to very repeating code in the data class, and if you are binding to the user interface, it is best to use the AOP approach and intercept calls to the properties you want to report. Most IoC containers have support for these kinds of things.

+6
source

This template is called Observer . In .Net, events are one implementation of this pattern. For a specific case of observing individual properties , the INotifyPropertyChanged interface should be used (as @Lee describes ).

+3
source

You do not say which GUI (WinForms, WPF) you use, but there is an INotifyPropertyChanged interface. There is a guide for MSDN too.

+2
source

You can simply use the built-in System.EventHandler . This is a pretty standard template. You still need to define an event for each property that you want to control, but you don't need a separate delegate.

+1
source

In Windows Forms, there are several ways to notify the GUI when some properties are processed using data binding.

There are several types of data binding in Windows Forms.

  • For simple data binding (a data source with one boud object to one control), you can use INotifyPropertyChanged or add events in this format: PropertyNameChanged for each property that you want to update in the GUI. And you should set the Binding.ControlUpdateMode property of OnPropertyChanged.

  • For complex data binding (a data source with many objects bound to a control that can display many objects), you must use all of (1), and you must use BindingSource or BindingList or manually implement IBindingList ;

For more information, you should see this wonderful book:

Chris Sells Windows Forms 2.0 Programming Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET from Brian Noyes

0
source

Source: https://habr.com/ru/post/1299199/


All Articles