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
Related
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.
I have a DataGrid that is bound to an ObservableCollection in the ViewModel. This is a search results DataGrid. The problem is that after I update the search results ObservableCollection the actual DataGrid is not updated.
Before I get down voted to nothing, please note this is NOT about data in the columns (that bind works perfectly) it is about clearing and then placing completely new data into ObservableCollection that is not updating the DataGrid. So linking to something like this will not help as my properties are working correctly
Background:
The ObservableCollection is declared in the ViewModel like this;
public ObservableCollection<MyData> SearchCollection { get; set; }
The search DataGrid that is bound to my search ObservableCollection like this;
<DataGrid ItemsSource="{Binding SearchCollection}" />
In the ViewModel I have a search method like this;
var results =
from x in MainCollection
where x.ID.Contains(SearchValue)
select x;
SearchCollection = new ObservableCollection<MyData>(results);
The method fires correctly and produces the desired results. Yet the DataGrid is not updated with the new results. I know the ViewModel has the correct data because if I put a button on the Page and in the click event put this code;
private void selectPromoButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
var vm = (MyViewModel)DataContext;
MyDataGrid.ItemsSource = vm.SearchCollection;
}
The DataGrid now correctly shows the results.
I know I could put some event in the code behind of the Page but wouldn't that defeat MVVM? What is the correct MVVM way to handle this?
Try to implement INotifyPropertyChanged in your modelview
example:
public abstract class ViewModelBase : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
}
protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
{
var handler = PropertyChanged;
handler?.Invoke(this, args);
}
}
public class YourViewModel : ViewModelBase {
private ObservableCollection<MyData> _searchCollection ;
public ObservableCollection<MyData> SearchCollection
{
get { return _searchCollection; }
set { _searchCollection = value; OnPropertyChanged("SearchCollection"); }
}
}
The problem is that your are resetting your SearchCollection property rather than updating the collection. Observable collection raises the correct change events when items in the list are added, deleted, or updated. But not when the collection property itself is changed.
In your SearchCollection setter, you can fire a PropertyChanged event. Just like any other property when it changes. Also make sure your DataGrid ItemsSource binding is one-way not one-time.
<DataGrid ItemsSource="{Binding SearchCollection, Mode=OneWay}" />
Or you can change the members of the collection (clearing the old results and adding new ones). That should also update the DataGrid as you expect.
From your code sample, I would go with the first option.
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.
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
I have a class:
public class A : INotifyPropertyChanged
{
public List<B> bList { get; set; }
public void AddB(B b)
{
bList.Add(b);
NotifyPropertyChanged("bList");
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(string info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
}
And a binding (DataContext of UserControl is an instance of A):
<ListBox ItemsSource="{Binding Path=bList}" />
Elements are shown, the ListBox is not updated after new object is added to List
After changing list to ObservableCollection and removing the NotifyPropertyChanged handler everything works.
Why the list is not working?
Your property has to be public, or the binding engine won't be able to access it.
EDIT:
After changing list to ObservableCollection and removing the NotifyPropertyChanged handler everything works.
That's precisely why the ObservableCollection<T> class was introduced... ObservableCollection<T> implements INotifyCollectionChanged, which allows it to notify the UI when an item is added/removed/replaced. List<T> doesn't trigger any notification, so the UI can't detect when the content of the list has changed.
The fact that you raise the PropertyChanged event does refresh the binding, but then it realizes that it's the same instance of List<T> as before, so it reuses the same ICollectionView as the ItemsSource, and the content of the ListBox isn't refreshed.
First thought is that you're trying to bind to a private member. That certainly doesn't seem right.
I think that the problem is that, although you are notifying the binding framework that the property has changed, the actual value of the property remains the same. That is to say that although the listbox may reevaluate the value of its ItemsSource binding, it will find that it is still the same object instance as previously. For example, imagine that the listbox reacts by to the property changed event somehow similar to the below.
private void OnItemsSourceBindingChanged()
{
var newValue = this.EvaluateItemsSourceBinding();
if (newValue != this.ItemsSource) //it will be equal, as its still the same list
{
this.AddNewItems();
}
}
In your example, this would mean that it would not reevaluate the items.
Note: I do not know how the listbox works with the ItemsSource property - I'm just speculating!
ObservableCollections send CollectionChanged events not PropertyChanged events
By signaling
NotifyPropertyChanged("bList");
you are basically saying you have a new list object, not that the content of the List has changed.
If you Change the type to ObservableCollection, the collections automatically sends
CollectionChanged
notifications that the collection items have changed, which is what you want.