Notify Gui that data class has changed - c#

In C#:
I have a data class that is shared amongst several gui classes. I would like all of the gui classes that use it to be notified when some of the properties change, so they can keep the GUI up to date.
In a couple of the properties I have added delegates that the GUI classes can listen to for updates. This seems to work ok.
The problem I have is that more and more of the properties will require GUI notification. When that happens I will have to add more delegates. It also seems that this is adding an extra responsibility to the data class that it has to manage.
Is there some common pattern that I can use to monitor this class to extract this notification responsibility from the data class?

The common way of doing this is for the data class to implement INotifyPropertyChanged.
EDIT: If you have a lot of properties, this can lead to very repetitive code in the data class, and if you are binding to a UI, it might be best to use an AOP approach and intercept calls to the properties that you want to notify on. Most IoC containers have support for this sort of thing.

The pattern is called Observer. In .Net, events are one implementation of that pattern.
For the specific case of observing individual properties, the INotifyPropertyChanged interface should be used (as #Lee describes).

You don't say what GUI framework (WinForms, WPF) you are using, but there is the INotifyPropertyChanged interface. There is an How to guide on MSDN too.

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

In Windows Forms there are several ways to notify GUI when some properties are chaged using Data Binding.
There are several types of Data binding in Windows Forms.
For simple data binding (data source with one object boud to one control) you can use INotifyPropertyChanged, or you can add events in this format: PropertyNameChanged for every property that you want update in GUI. And you should set Binding.ControlUpdateMode property to OnPropertyChanged.
For complex data binding (data source with many objects bound to control that can display many objects) you should use all from (1) and you should use BindingSource or BindingList or manually implement IBindingList;
For more information you should see this great books:
Windows Forms 2.0 Programming by Chris Sells
Data Binding with Windows Forms 2.0: Programming Smart Client Data Applications with .NET by Brian Noyes

Related

Should I use ObservableCollections in the Model in MVVM?

I'm using MVVM for a WPF client that represents a model and allows users to interact with it. I've always shied away from using the ObservableCollection class in the actual model (opting for generic collections like IList inside that model instead, and then converting that IList to the actual data-bound ObservableCollection on the ViewModel when the underlying collection changes). Reason being that MSDN presents the class as WPF and UI-centric:
You can enumerate over any collection that implements the IEnumerable
interface. However, to set up dynamic bindings so that insertions or
deletions in the collection update the UI automatically, the
collection must implement the INotifyCollectionChanged interface. This
interface exposes the CollectionChanged event, an event that should be
raised whenever the underlying collection changes. WPF provides the
ObservableCollection class, which is a built-in implementation of a
data collection that implements the INotifyCollectionChanged
interface.
Question: Is my distinction actually necessary? It's extra work and extra code. I understand that this topic might be too vague and subjective for SO, but maybe there are clear, universally agreed-upon conventions everybody follows.
Yes I think you are doing it right. Observable collections belong at the presentation layer. Add them to your view model, not your domain model.
This question may be of some help
but maybe there are clear, universally agreed-upon conventions everybody follows.
Please let me know when you find them, thx.
Is my distinction actually necessary?
It depends on what a model really is in this case, or rather how you define a model.
If it is some kind of domain business object that is defined in an assembly that is referenced by your business or service layer and may be used across your entire domain, it shouldn't implement any kind of client-specific interfaces such as INotifyCollectionChanged.
Then you should prefer to use a generic type such as IList and then create a wrapper class in the client application that you bind to the view element to.
But if the model is a class that is used only inside your client application and not in any other tiers of your application, then you might as well define the collection property as an ObservableCollection and bind to this one directly.
The point is that a domain business object should not have any knowledge of WPF or the fact that a client application may bind to it. That's why it seldom makes sense to bind directly to such objects in a WPF application without wrapping them in WPF-aware view model classes first.
This does add some extra work and an additional class but at the same time it helps maintain separation of concerns which is usually good for maintenance.
In an enterprise scenario it is also pretty common that the business object may contain business logic that you don't want to expose to the client and it also may contain additional properties that it makes no sense to expose to the view. So then you still need to wrap it in another class even if the collection property should actually return an ObservableCollection.
So if your question is "should I use ObservableCollections in the business objects" the answer is no.

c# Best way to communicate between classes

Right now I am coding an application and am thinking that there has to be a better solution to what I am doing right now.
I have a main window which shall handle the settings of the program. Then I have further classes and windows. For example a language handler class and a form that is handling the user input needed for the "main function".
However, until now I always have to pass my main window to each of this classes, because the language handler shall be able to change the main window's strings. And the other form should also be able to pass data to the main Window.
If we imagine there will be much more classes and every class needs a copy of the main window this would consume a lot of resources depending on the main window's "size".
So, is there a better/more efficient way to communicate between these classes.
Common way to do that is to use observer pattern, which in .NET is events system. Simply said, your classes subscribe to each other's events and perform action when event is raised. As noted in comment, passing references is not memory heavy, but it results in tight coupling between different pieces of your code - observer pattern addresses that problem.
Another option is to consider you classes as services. Code them to an interface and then use dependency injection (aka Inversion of Control) to build up the object graph (You tell the IoC container you want a frmSomething and it will determine what services/classes it needs and instantiate them as appropriate).
This means that:
you only ever have to code against an interface not an implementation
your code is loosely coupled (You can swap an OldTranslator for a NewTranslator and as long as they both comply to the same interface, nothing has to be changed except the configuration of the container)
you can develop high-level features which rely on services that haven't been written yet and your code will compile
You can very easily change how your app works, at run-time if needs be, by changing what classes/services are registered in your container.
Have a look at Unity for the MS-Supported DI container. Castle Windsor is a popular alternative but there are many more
It's worth noting that passing a "Copy" of the main window around as you've said is not a bad thing - You're actrually only passing a reference (effectively a pointer) to the main window (since anything more complex than the real primitives are reference types). This means that there's very little overhead whatsoever
I would suggest you to use Galasoft or Prism MVVM implementations. There you can use their messaging service which is quite easy to use. The class that needs info just sends a message to the subscriber and they in turn can send all data needed. I think that this is the easiest way to handle communication.
in addition to the ans given by IVAN.. if we look at a higher level view without all those terminologies then you should probably create a static class which would server as InMemoryStorage and defines fields on it to save information
this what you will have complete control over what is being shared and multiple components can change it
moreover you can defined getters and setters and raise an event whenever the property is changed so that different forms or windows (views) can subscribe to the change and take action accordingly

INotifyPropertyChanged usage outside data binding

I've never used INotifyPropertyChanged, and I'm considering using it widely throughout a new application.
My question is, is it 'proper' to use INotifyPropertyChanged interface in order to provide event notifications for things other than databound controls?
It seems from a bunch of examples online that this interface is widely used for notifying grids and such for when data is changed. I have various scenario's where I need other classes to be notified of data changes in other classes, and I was wondering if you think it's cleaner to implement this interface, and perform the changed call on setters, or rather just create regular events.
When making a choice like this, I lean towards using language features over other constructs.
A severe downside to INotifyPropertyChanged is that it only provides the property name as a string on update, and your consuming classes have to parse that string and decide how to act on it.
With events you can provide any kind of delegate signature that the event requires and the consuming classes can act on that change directly.
If you peek under the hood, you'll find that INotifyPropertyChanged is an event anyway, so why not use events directly?
I think you can use this Interface for those scenarios but you have to really think hard about if you want this thight coupeling between your classes.
If this makes sense to you - sure, why reinvent the wheel?
I think you should go ahead an implement the INotifyPropertyChanged interface, just because it's there for that purpose and its what the UI uses to pickup changes, there's no need to create custom events yourself.
WPF and Silverlight both use INotifyPropertyChanged extensively in the data binding system. If your are going to databind to your objects, you should definetely use INotifyPropertyChanged. |
Otherwise, as far as I know, it does not influence .NET Framework technologies.
INotifyPropertyChanged is not the cleanest way of notifying when your property changes, depending on how you look at it, since there is one event and a string with the propertyname, you will have to make a switch statement. It sure is easier to implement comparing to events per property though
I would not use INotifyPropertyChanged for anything except databinding. This interface is probably the only option for databinding because controls which will act on PropertyChanged event do not know sender's type in advance. Because of that databinding has to use such a generic interface.
For my own types and scenarios I would use regular events (one event per each property which can change its value). INotifyPropertyChanged in such scenarios is kind of stringly typed code. You can see that even WPF itself is still full of oldscool events (FrameworkElement for example with a lot of ***Changed events).
Dont use is in other scenarios, if you need to notify other domain classes use domain events instead, which would be more business oriented and descriptive and strongly typed
I am not a fan of INPC outside of the UI realms as it hides the fact that significant events are being generated by instances of the object. Also, if I use your class implementing INPC, I will expect all properties to broadcast notifications, if only some of them do, that's a bug at runtime that can go unnoticed.

What is the best way to do validations in windows forms

What is the best way to do validation in a windows forms application?
What is the easiest way?
What is the most attractive (to the end user) way?
Regards,
-Kushan-
Concerning UI validation, I have a set of control validators, and I just plug 'em in where I need them by assigning their control. You can show errors using ErrorProvider, all you need is encapsulated framework to automate things.
First there is the ValidatorBase class. Make it abstract and inherit the Component class so you can have design time support. Store a private instance of ErrorProvider here, and use something like Template Method pattern (create a Validate method, which in turn calls the protected abstract DoValidation method). In concrete implementations of the base class just override the DoValidation and put your logic here. You can have EmptyValidator (check if control's value isn't empty), RegexValidator (check controls value with some reg. expression), GroupValidator (do Validate on every ValidatorBase instance in some list), whatever you want.
In the base class, you can add things like design-time support for properties (the error message, icon, control to validate etc...)
EDIT1: Now, concerning validation other then in the UI, that is the domain of your business layer, and your rules. There are frameworks / patterns for those things too, but I think you are asking about the UI validation.
EDIT2: ASP.NET has a set of similar validators built-in, although with more functionalities (client side validation, etc...), but to be honest, I don't like them that much.
EDIT3: also check:
Is there any validation control available in .net win forms like asp.net web form?
One interface you might consider looking at is IDataErrorInfo along with the ErrorProvider class. I've got an old blog post that provides a list of the DataBinding classes and interfaces that might help: Data Binding Classes, Interfaces, and Attributes in Windows Forms 2.0.

Update UI from external event

First of i am not a UI developer and this is probably a very simple problem.
What i have is a external service that I subscribe to an event, when ever that event fires a service picks this up, manipulates the data in some way then gives the UI the data to display
What i am unsure of is how to archetect this and keep the dependancy between the service which will tell the UI to update and the UI as loose as possible.
Can anyone suggest a stratagy for this or post me some links on examples or an open source project to actually look at some working code.
I am using c# and ether wpf or winforms for this.
Cheers
Colin G
How simple is this application?
The simplest solution is to have the data access/manipulation in one object, and have the UI passed as an interface into that object. With the UI interface methods, you can give data to the UI but let the UI handle displaying the data in a GUI thread-safe manner.
If it's a more complex application, I'd say it would make more sense to look into something like MVC or MVP. Or MVVM for WPF, maybe look at Bea Costa's blog for databinding examples.
My solution to this problem is to create a timer in your ui, and have your ui subscribe to the 'onTick' method. Then, at every timer tick, have the UI look at the service and figure out what data to display.
There's a lot of ways to skin this cat, but without knowing a little more about your requirements and your existing infrastructure, let me suggest you use an EventBroker / Mediator for this. This is an easy way to implement a kind of Publisher / Subscriber type of relationship without worrying about too much of the plumbing.
If you are using Prism, I'd suggest using the EventAggregator.
If not, you might consider using the "Messenger" implementation of an EventBroker available with the MVVMFoundation stuff that John Smith wrote. It's not really dependent on you using MVVM or WPF and does what you are looking for:
http://mvvmfoundation.codeplex.com/
Hope this helps.
then gives the UI the data to display...
I would suggest you to have a service agent layer which will raise an event and pass a DTO. This event should be subscribed by the layer which contains objects bound to the UI. Once this layer receives the DTO, update the UI.

Categories

Resources