Singleton OnPropertyChanged Not Firing - c#

I have a class called DataModel where I am storing an ObservableCollection of projects. I was using a static ObservableCollection, but since I want to bind to it, and OnPropertyChanged doesn't seem to work correctly for static properties, I created it as a singleton:
public sealed class DataModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private static readonly DataModel instance = new DataModel();
private DataModel() { }
public static DataModel Instance
{
get
{
return instance;
}
}
#region Projects
private ObservableCollection<Project> projects = new ObservableCollection<Project>();
public ObservableCollection<Project> Projects
{
get
{
return projects;
}
set
{
if (projects == value)
{
return;
}
projects = value;
OnPropertyChanged("Projects");
}
}
#endregion Projects
public void OnPropertyChanged(string name)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(name));
}
}
Then when I click a button,
Project newProject = new Project() { Title = "Test" };
DataModel.Instance.Projects.Add(newProject);
From what I could come up with from various sources, this ought to work correctly. However, the OnPropertyChanged event is never called. If I do
DataModel.Instance.Projects = new ObservableCollection<Project>();
it is called. But adding a Project to the collection won't call it.

OnPropertyChanged is only automatically fired when that property is reassigned. That is why reassigning your entire collection causes it to be fired. Modifying the collection fires the collection's own CollectionChanged event instead, since you're not actually changing the Projects reference, just mutating the same collection it's referring to.
If your collection is bound to a control's ItemsSource property correctly, e.g.
<ListView ItemsSource="{Binding Projects}"/>
where the data context is your DataModel instance, you should not need to do anything beyond adding the new item.
If you need to do something when the collection is changed, subscribe to its CollectionChanged event instead:
private DataModel()
{
Projects.CollectionChanged += Projects_CollectionChanged;
}
private void Projects_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
// An item was added...
}
}

I expect it NOT to work. Because you are adding item to Observation collection in which case there is no reason setter would be called and thus OnPropertyChanged. That's why it works when you initialize DataModel.Instance.Projects from calling code. You could call property changed explicitly as below:
Project newProject = new Project() { Title = "Test" };
DataModel.Instance.Projects.Add(newProject);
DataModel.Instance.OnPropertyChanged("Projects");
Disclaimer: Although this is possible, you really need not do this. That is why they have provided us with ObservableCollection. Any item/s added or removed to/from such collection are automatically notified to the View. If this was not true, why would anybody use ObservableCollection instead of simple List for data bindings.

Related

INotifyPropertyChanged does not work from class held in ObservableCollection<Class>

I have a class, "BaseClass" that implements INotifyPropertyChanged and has the following:
BaseClass:
private bool isOn;
public bool IsOn
{
get { return isOn; }
set
{
isOn = value;
RaisePropertyChanged("BaseClass:IsOn");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
I then have a class, "DIClass" that also implements INotifyPropertyChanged. It also has an ObservableCollection<BaseClass>:
DIClass:
public ObservableCollection<BaseClass> ClassesOfA;
private string iNPCTest;
public string INPCTest
{
get { return iNPCTest; }
set
{
iNPCTest = value;
RaisePropertyChanged("DIClass: INPCTest");
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected void RaisePropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
My ViewModel holds an intance of "DIClass" and registers to it's PropertyChanged event. When I set the value of INPCTest in "DIClass", the ViewModel 'captures' the event correctly. However when I updated the IsOn property within the ObservableCollection, as below, the event is not picked up in the ViewModel.
ClassesOfA[0].IsOn = true;
Why is the INPC interface not working with the nested property? The question and answer here seems quite relevant, but I can't figure it out.
EDIT: additional explanation and code:
I can register to the PropetyChanged events of the ObservableCollection's items, as such:
ClassesOfA[0].PropertyChanged += DIClass_PropertyChanged;
ClassesOfA[1].PropertyChanged += DIClass_PropertyChanged;
However, this still does not bubble up to notify my ViewModel, that a property of my DIClass's ObservableCollection<BaseClass> has changed. I want to use INPC to bubble up event information / property updates up via MVVM layers. But I want to "wrap" them to make my classes cleaner/ less properties lying around
EDIT:
I add this "sketch" of my problem/scenario, with basic naming to make it easy:
To answer your question: This is by design.
ObservableCollection has two events:
CollectionChanged: Fires when the collection changes, e.g. collection.Add( item )
PropertyChanged: Fires when the property changes, e.g. collection = new ObservablecCollection<T>();
I think you need no ObservableCollection, because - as far as I understand your question - you want to observe the changes of the properties of the items in the collection. To achieve that you need to register to each observed item's PropertyChanged like this:
public List<BaseClass> Collection {get;set;}
public void InitializeCollection( IEnumerable<BaseClass> baseClassCollection){
Collection = new List<BaseClass>();
foreach(var item in baseClassCollection){
item.PropertyChanged += MethodToCallOnPropertyChanges;
Collection.Add( item );
}
}
public void MethodToCallOnPropertyChanges(object sender, PropertyChangedEventArgs e){
//react to any property changes
doSomething();
//react to specific properties
if(e != null && e.PropertyName.Equals("isOn"))
doSomethingOtherStuff();
}
This can be very annoying and can causes some other problems.
If I would come across this, I would think about redesigning the ViewModels and the UI. I would try to have an UI which is bound to each BaseClass item. For example, if I have an ListView I would provide an ItemTemplate in which the BaseClass item is bound. Doing so would prevent the need of registering to each item's PropertyChanged.
My suggestion is that you could create a customized ObservableCollection class that raises a Reset action when a property on a list item changes. It enforces all items to implement INotifyPropertyChanged.
I made a simple demo and you that you could check:
public class DIClass : INotifyPropertyChanged
{
public ExObservableCollection<BaseClass> ClassesOfA
... other code...
}
public sealed class ExObservableCollection<T> : ObservableCollection<T>
where T : INotifyPropertyChanged
{
public ExObservableCollection()
{
CollectionChanged += AllObservableCollectionCollectionChanged;
}
public ExObservableCollection(IEnumerable<T> pItems) : this()
{
foreach (var item in pItems)
{
this.Add(item);
}
}
private void AllObservableCollectionCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.NewItems != null)
{
foreach (Object item in e.NewItems)
{
((INotifyPropertyChanged)item).PropertyChanged += ItemPropertyChanged;
}
}
if (e.OldItems != null)
{
foreach (Object item in e.OldItems)
{
((INotifyPropertyChanged)item).PropertyChanged -= ItemPropertyChanged;
}
}
}
private void ItemPropertyChanged(object sender, PropertyChangedEventArgs e)
{
NotifyCollectionChangedEventArgs args = new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, sender, sender, IndexOf((T)sender));
OnCollectionChanged(args);
}
}
Then you could use the ExObservableCollection class in the DIClass object. When the properties inside the BaseClass changes, the UI will be updated.
Update:
Finally, I found out the unexpected behavior you mentioned based on the complex sample. The ExObservableCollection class works well and fires the property changed event correctly.
The key point is you think if the property change event in baseclass is fired then it will
trigger the property change event in DIClass as well, right? I have to say that is not correct. The property change event only fires in the current class. It won't pass to the parent class unless you handle it in the parent class. It fired only once and notify the UI when the target property is changed.
If I understand your scenario correctly, you want to change the ToggleButton's status when the same property in BaseClassobject is changed. But the ToggleButtons are bind to VMData objects so that you need to get notified when the BaseClass objects are changed in the DIClass objects. So you want the the property change event of BaseCasss triggers the property change event of the DIClass.
Handling the property changed event of BaseClass in the DIClass object is the correct way to do what you want. It's the same like handling DIClass event in the ViewModel. But you don't want it since there might be many objects.
Then the first version of your sample is the recommended way to achieve what you want by triggering the property changed event of the DIClass on your own.

Win RT - updating view when item in observable collection changed

In my windows store app I have a gridview with data source set to Observable collection. When the item is added or removed to the collection everything works fine and view is updated. However when property of item of the collection is changed, the collectionChanged event is not fired and the views is not updated. I found a solution how to use INotifyChanged and propertyChanged event, but I want to fluidly update the view without doing something as reassigning the data source of gridview in propertyChanged Handler.
So I want to ask, if there is any solution to this problem.
Thank You in advance.
Refer the below code snippet, to notify while collection changed.
public class MyClass : INotifyPropertyChanged
{
private ObservableCollection<double> _myCollection;
public ObservableCollection<double> MyCollection
{
get { return _myCollection; }
set
{
_myCollection = value;
RaisedOnPropertyChanged("MyCollection");
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void RaisedOnPropertyChanged(string _PropertyName)
{
if (PropertyChanged!=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(_PropertyName));
}
}
}
Hope it will help you..!
Regards,
Joy Rex

The same property in two ViewModels and the property changed

I have three ViewModels:
- MainViewModel,
- NavigatorViewModel,
- ProjectViewModel.
In the MainViewModel I have a property called CurrentProject from type ProjectViewModel:
public ProjectViewModel CurrentProject
{
get
{
return _currentProject;
}
set
{
if (_currentProject == value)
{
return;
}
_currentProject = value;
RaisePropertyChanged("CurrentProject");
}
}
In the NavigatorViewModel I have also a property CurrentProject
public ProjectViewModel CurrentProject { get { return ViewModelLocator.DesktopStatic.CurrentProject; } }
I use MVVM light. The View NavigatorView doesnt get notified if the property CurrentProject in the MainViewModel is changed.
How can I let the NavigatorView know, that the property has changed?
As a design concern, I would recommend not using a static Singleton pattern for this. You could use the Messenger class to send messages.
However, to address your current problem, you need to respond to the PropertyChanged event on the Singleton for that property:
public class NavigatorViewModel : INotifyPropertyChanged
{
public NavigatorViewModel()
{
// Respond to the Singlton PropertyChanged events
ViewModelLocator.DesktopStatic.PropertyChanged += OnDesktopStaticPropertyChanged;
}
private void OnDesktopStaticPropertyChanged(object sender, PropertyChangedEventArgs args)
{
// Check which property changed
if (args.PropertyName == "CurrentProject")
{
// Assuming NavigatorViewModel also has this method
RaisePropertyChanged("CurrentProject");
}
}
}
This solution listens for changes to the Singleton property and propagates the change to listeners of NavigatorViewModel.
Warning: Somewhere in the NavigatorViewModel you need to unhook the event or you risk a memory leak.
ViewModelLocator.DesktopStatic.PropertyChanged -= OnDesktopStaticPropertyChanged;

Update automatic ListBox items when alter List<T>

I have a ListBox, I populate it with ItemsSource with List<Control>.
But when I delete or add new control for this List, I need every time reset my ListBox ItemsSource
Have any method for ListBox sync List content?
Instead of using a List<T>, use an ObservableCollection<T>. It is a list that supports change notifications for WPF:
// if this isn't readonly, you need to implement INotifyPropertyChanged, and raise
// PropertyChanged when you set the property to a new instance
private readonly ObservableCollection<Control> items =
new ObservableCollection<Control>();
public IList<Control> Items { get { return items; } }
In your Xaml, use something like this...
<ListBox ItemsSource="{Binding MyItemsSource}"/>
And wire it up like this...
public class ViewModel:INotifyPropertyChanged
{
public ObservableCollection<Control> MyItemsSource { get; set; }
public ViewModel()
{
MyItemsSource = new ObservableCollection<Control> {new ListBox(), new TextBox()};
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
This will present the items to the ListBox. In the example here, the collection contains a ListBox and a TextBox. You can add/delete from the collection and get the behaviour you are after. Controls themselves are not all that great as ListBox items because they do not have a meaningful way of populating a visual. So you will probably need to run them through an IValueConverter.
Implement INotifyPropertyChanged interface in your viewmodel.
Post that in the setter of this List, call the NotifyPropertyChanged event. This will
result in updating your changes on UI

List<string> INotifyPropertyChanged event

I have a simple class with a string property and a List property and I have the INofityPropertyChanged event implemented, but when I do an .Add to the string List this event is not hit so my Converter to display in the ListView is not hit. I am guessing the property changed is not hit for an Add to the List....how can I implement this in a way to get that property changed event hit???
Do I need to use some other type of collection?!
Thanks for any help!
namespace SVNQuickOpen.Configuration
{
public class DatabaseRecord : INotifyPropertyChanged
{
public DatabaseRecord()
{
IncludeFolders = new List<string>();
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
protected void Notify(string propName)
{
if (this.PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propName));
}
}
#endregion
private string _name;
public string Name
{
get { return _name; }
set
{
this._name = value;
Notify("Name");
}
}
private List<string> _includeFolders;
public List<string> IncludeFolders
{
get { return _includeFolders; }
set
{
this._includeFolders = value;
Notify("IncludeFolders");
}
}
}
}
You should use ObservableCollection<string> instead of List<string>, because unlike List, ObservableCollection will notify dependents when its contents are changed.
And in your case I'd make _includeFolders readonly - you can always work with one instance of the collection.
public class DatabaseRecord : INotifyPropertyChanged
{
private readonly ObservableCollection<string> _includeFolders;
public ObservableCollection<string> IncludeFolders
{
get { return _includeFolders; }
}
public DatabaseRecord()
{
_includeFolders = new ObservableCollection<string>();
_includeFolders.CollectionChanged += IncludeFolders_CollectionChanged;
}
private void IncludeFolders_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
{
Notify("IncludeFolders");
}
...
}
The easiest way to make WPF's list binding work is to use a collection that implements INotifyCollectionChanged. A simple thing to do here is to replace or adapt your list with an ObservableCollection.
If you use ObservableCollection, then whenever you modify the list, it will raise the CollectionChanged event - an event that will tell the WPF binding to update. Note that if you swap out the actual collection object, you will want to raise the propertychanged event for the actual collection property.
Your List is not going to fire the NotifyPropertyChanged event automatically for you.
WPF controls that expose an ItemsSource property are designed to be bound to an ObservableCollection<T>, which will update automatically when items are added or removed.
You should have a look at ObservableCollection

Categories