Windows phone 8 MVVM Linq table Creates new instance on NotifyPropertyChanging - c#

I have a Linq DataContext as a database for the application. I have set up the MVVM pattern and am able to insert new records into the database. However when I load these records and try update them a new instance of the record is being created in the background and being updated with the property changes. So when they UI is invoking the save command the originally loaded instance of the record has no changes and is not saved.
from what I can tell this is the sequence of events
Load Instance 1
Start updating property
NotifyPropertyChanging is called
New instance2 is loaded
New Instance2 is updated
Invoke save changes from UI for Instance 1
No changes are made because Instance 1 has not been updated
Below is the code I have:
/* This is the Entity */
[Table]
public class User : IDisposable, INotifyPropertyChanged, INotifyPropertyChanging
{
private MyDataContext context;
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
public event PropertyChangingEventHandler PropertyChanging;
private void NotifyPropertyChanging(String propertyName)
{
PropertyChangingEventHandler handler = PropertyChanging;
if (null != handler)
{
handler(this, new PropertyChangingEventArgs(propertyName));
}
}
public void Dispose()
{
context.Dispose();
}
private Guid _id;
[Column(IsPrimaryKey = true, IsDbGenerated = false, DbType = "UNIQUEIDENTIFIER NOT NULL", CanBeNull = false, AutoSync = AutoSync.OnInsert)]
public Guid Id
{
get { return _id; }
set
{
if (_id != value)
{
NotifyPropertyChanging("Id");
_id = value;
NotifyPropertyChanged("Id");
}
}
}
private string _name;
[Column(CanBeNull = false)]
public string Name
{
get { return _name; }
set
{
if (_name != value)
{
NotifyPropertyChanging("Name"); // This line creates the new entity
_name = value;
NotifyPropertyChanged("Name");
}
}
}
public User()
{
this.context = MyDataContext.GetContext();
}
public override void SaveChanges()
{
if (_id == Guid.Empty)
{
this.Id = Guid.NewGuid();
context.Users.InsertOnSubmit(this);
context.SubmitChanges();
}
else
{
context.SubmitChanges();
}
}
public static User NewInstance()
{
return new User
{
Name = String.Empty
};
}
}
/* This is the data context */
public class MyDataContext : DataContext
{
// Specify the connection string as a static, used in main page and app.xaml.
public static string ConnectionString = "Data Source=isostore:/MyApp.sdf;Password=pwd";
public MyDataContext(string connectionString) : base(connectionString) { }
public static MyDataContext GetContext()
{
var context = new MyDataContext(ConnectionString);
return context;
}
public Table<User> Users;
}
/* This is the View Model */
public sealed class UserViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
private User _user;
public UserViewModel(Guid id)
{
using (MyDataContext context = new MyDataContext(MyDataContext.ConnectionString))
{
_User = context.User.First(u => u.Id == id);
}
}
public UserViewModel(User user)
{
_user = user;
}
public UserViewModel()
{
_user = User.NewInstance();
}
public string Name
{
get { return _user.Name; }
set
{
_user.Name = value;
NotifyPropertyChanged("Name");
}
}
private ICommand _saveCommand;
public ICommand SaveCommand
{
get
{
return _saveCommand ?? (_saveCommand = new GenericCommand(() =>
{
_user.SaveChanges();
}, true));
}
}
}

In your MyDataContext I would think you want the below instead, a basic singleton concept so that you're working on the same object and thus saving the same object with changes.
private static DataContext context = null;
public static MyDataContext GetContext()
{
if(context == null)
context = new MyDataContext(ConnectionString);
return context;
}
edit- Note, this can have a major impact on your application in the big picture. May need to redesign when a new one is created, and if/when you should specifically set it to null.

Related

Calling generic method from viewmodel

I'm pretty new to generics, and MVVM as well. Working on this for a project at school, and my problem might be that I'm trying to impress a bit much. I think I may have coded myself into a hole, but I'm hoping you all can help me get out of it.
I've created a dbcontext, a dataservice, and now I'm trying to get them to play nicely in my viewmodel - I'm getting nowhere.
DbContextFactory:
public class TimeKeeprDbContextFactory : IDesignTimeDbContextFactory<TimeKeeprDbContext>
{
public TimeKeeprDbContext CreateDbContext(string[] args = null)
{
var options = new DbContextOptionsBuilder<TimeKeeprDbContext>();
options.UseSqlServer("Server=(localdb)\\MSSQLLocalDB;Database=TimeKeeprDB;Trusted_Connection=True;");
return new TimeKeeprDbContext(options.Options);
}
}
DbContext:
public class TimeKeeprDbContext : DbContext
{
public TimeKeeprDbContext(DbContextOptions options) : base(options) { }
public DbSet<User> Users { get; set; }
public DbSet<Event> Events { get; set; }
}
DataService:
public class DataService<T> : IDataService<T> where T: DomainObject
{
private readonly TimeKeeprDbContextFactory _contextFactory;
public DataService(TimeKeeprDbContextFactory contextFactory)
{
_contextFactory = contextFactory;
}
public async Task<T> Create(T entity)
{
using TimeKeeprDbContext context = _contextFactory.CreateDbContext();
EntityEntry<T> createdResult = await context.Set<T>().AddAsync(entity);
await context.SaveChangesAsync();
return createdResult.Entity;
} [...]
BaseViewModel:
public class BaseViewModel : INotifyPropertyChanged
{
#region WindowProperties
[.....]
#endregion
#region PropertyChanged
protected void OnPropertyChanged<T>(Expression<Func<T>> action)
{
var propertyName = GetPropertyName(action);
OnPropertyChanged(propertyName);
}
private static string GetPropertyName<T>(Expression<Func<T>> action)
{
var expression = (MemberExpression)action.Body;
var propertyName = expression.Member.Name;
return propertyName;
}
private void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
ViewModel:
public class MainViewModel : BaseViewModel
{
private string _firstname;
private string _lastname;
public string FirstName
{
get => _firstname;
set
{
_firstname = value;
OnPropertyChanged(() => FirstName);
}
}
public string LastName
{
get => _lastname;
set
{
_lastname = value;
OnPropertyChanged(() => LastName);
}
}
public ICommand CreateCommand { get { return new BaseCommand(Click); } }
private void Click()
{
User user = new User()
{
FirstName = _firstname,
LastName = _lastname
};
//call Create<T> from DataService
ShowMessageBox($"{user.FirstName} {user.LastName}"); //just to make sure the object is ok
}
}
I've tried about a million things, but I just can't seem to wrap my head around what I need to do in order to call 'Create(user)' from DataService in the viewmodel. Can someone maybe point me in the right direction?
PS I've googled until my fingers bled, but it hasn't helped that much, unfortunately.
Hard to tell because I don't know all the frameworks or nuget packages you are using. But from what I can see, you just need to instantiate your DataService somewhere in your MainViewModel, then call its Create method where you've placed your comment //call Create<T> from DataService.
//Instantiate your DataService somewhere
var service = new DataService<User>(new TimeKeeprDbContextFactory());
//call Create<T> from DataService
service.Create(user);
If you see a squigly line under service.Create(user) indicating that this call is not awaited, you can fix that by making your function async/await like this.
private async void Click()
{
User user = new User()
{
FirstName = _firstname,
LastName = _lastname
};
//Instantiate your DataService somewhere
var service = new DataService<User>(new TimeKeeprDbContextFactory());
//call Create<T> from DataService
await service.Create(user);
ShowMessageBox($"{user.FirstName} {user.LastName}"); //just to make sure the object is ok}```
}

c# convert ObservableCollection to another type

I have the following problem that has got me stuck. In the below example I'm creating class A and class B and inheriting class A from class B. I then create an ObservableCollection<A> to hold a collection of people. What I then wish to do is expand class A to include the properties in class B and create this as a referenced copy ObservableCollection which I can update.
The error I'm getting when this complies is:
Unable to cast object of type
'<CastIterator>d__b1'1[iheriatance_obseravale_collection.Form1+B]' to
type
'System.Collections.ObjectModel.ObservableCollection'1[iheriatance_obseravale_collection.Form1+B]'.
public class A : INotifyPropertyChanged
{
string _firstName;
public string firstName
{
get
{
return _firstName;
}
set
{
if (_firstName != value)
{
_firstName = value;
NotifyPropertyChanged("firstName");
}
}
}
string _surname;
public string surname
{
get
{
return _surname;
}
set
{
if (_surname != value)
{
_surname = value;
NotifyPropertyChanged("surname");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string PropName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropName));
}
}
}
public class B : A, INotifyPropertyChanged
{
bool _isSelected;
public bool isSelected
{
get
{
return _isSelected;
}
set
{
if (_isSelected != value)
{
_isSelected = value;
NotifyPropertyChanged("isSelected");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string PropName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(PropName));
}
}
}
ObservableCollection<A> peopleColl = new ObservableCollection<A>();
private void addData()
{
peopleColl.Add(new A() { firstName = "James", surname = "Smith" });
peopleColl.Add(new A() { firstName = "John", surname = "Woods" });
}
ObservableCollection<B> selectedPeople;
private void selectAllPeople()
{
selectedPeople = (ObservableCollection<B>)peopleColl.Cast<B>();
foreach (B person in selectedPeople)
{
person.isSelected = true;
Console.WriteLine("Surname:{0}, IsSelected:{1}", person.surname, person.isSelected);
}
}
Many thanks
Stuart Turbefield
You have to iterate the source, cast each object, then create a new collection :
selectedPeople = new ObservableCollection<B>(peopleColl.OfType<B>());
this works only if peopleColl contains B objects. If it contains only A, you need to create new instances of B from A :
selectedPeople = new ObservableCollection<B>(peopleColl.Select(i => new B(i));
public class B : A
{
public B()
{
}
public B(A a)
{
this.firstName = a.firstName;
this.surname = a.surname;
}
}
Just for info, if A implements INotifyPropertyChanged, and if B inherits from A, there's no need to implement INotifyPropertyChanged again in the B class.

Update data in MVVM periodically and automatically

In my Model and ViewModel for XAML View (List), I have a String property.
The data are retrieved in LoadData from a WebService.
I don't use MVVMlight.
Model:
public class LocationsModel : INotifyPropertyChanged
{
private string _name;
public string Name
{
get
{
return _name;
}
set
{
if (value != _name)
{
_name = value;
NotifyPropertyChanged("Name");
}
}
}
private string _id;
public string ID
{
get
{
return _id;
}
set
{
if (value != _id)
{
_id = value;
NotifyPropertyChanged("ID");
}
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
ViewModel:
public class MainViewSurroundingModel : INotifyPropertyChanged
{
public MainViewSurroundingModel()
{
this.Items = new ObservableCollection<LocationsModel>();
}
public ObservableCollection<LocationsModel> Items { get; set; }
private string _name = "";
private string _id = "";
public string Name
{
get
{
return _name;
}
set
{
if (value != _name)
{
_name = value;
NotifyPropertyChanged("Name");
}
}
}
public string ID
{
get
{
return _id;
}
set
{
if (value != _id)
{
_id = value;
NotifyPropertyChanged("ID");
}
}
}
public bool IsDataLoaded
{
get;
private set;
}
public async Task<bool> LoadData()
{
// WEB-API CALL IS HERE...
this.IsDataLoaded = true;
return true;
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
I now want to update the Name property periodically by code (not re-retrieving data from WebService) every 5 minutes.
How and where can I implement this?
Sorry for vague answer, don't have much time so if anyone else cares to write more about what I said, they are welcome to it.
How to
One of the possibilities is using DispatcherTimer (more about it for example here) and using it's Tick event.(there is a tutorial in the link provided)
Now about where to create your timer.
It depends on what you want to change and when you want to start it.
If I'd like to change ALL of the data in the list some predefined way, i can do it like this:
public class MainViewSurroundingModel : INotifyPropertyChanged
{
//...omitted the parts you have done, only writing the things I'd change...
MainViewSurroundingModel()
{
..if there was something leave it here..
changeTimer = new DispatcherTimer...
changeTimer.Tick += Tick;
changeTimer.Interval = ....et cetera, setting the timer based on tutorial
}
public ObservableCollection<LocationsModel> items;
public ObservableCollection<LocationsModel> Items
{
get //edited so that I can write my own setter
{
return items;
}
set
{
if(value != items)
{
items = value;
//NotifyPropertyChanged("Items"); //can be used here, not necessary
changeTimer.Start();
}
}
}
private DispatcherTimer changeTimer;//based on the tutorial
//based on the tutorial provided, create dispatcher timer and
//tick definition somewhere around here
private Tick(...)
{
//code that iterates through the list and updates it goes here!
}
}

c# object with a ValueChanged event that fires when each property is changed

What is the best way to create a class with an event that fires when one of its Properties is changed? Specifically, how do you convey to any subscribers which Property was changed?
Ex:
public class ValueChangedPublisher
{
private int _prop1;
private string _prop2;
public static event ValueChangedHandler(/*some parameters?*/);
public int Prop1
{
get { return _prop1; }
set
{
if (_prop1 != value)
{
_prop1 = value;
ValueChangedHandler(/*parameters?*/);
}
}
}
public string Prop2
{
get { return _prop2; }
set
{
if (_prop2 != value)
{
_prop2 = value;
ValueChangedHandler(/*parameters?*/);
}
}
}
}
public class ValueChangedSubscriber
{
private int _prop1;
private string _prop2;
public ValueChangedSubscriber()
{
ValueChangedPublisher.ValueChanged += ValueChanged;
}
private void ValueChanged(/*parameters?*/)
{
/*how does the subscriber know which property was changed?*/
}
}
My goal is to make this as extensible as possible (e.g. I don't want a bunch of huge if/else if/switch statements lumbering around). Does anybody know of a technique to achieve what I'm looking for?
EDIT:
What I'm really looking for is how to utilize the INotifyPropertyChanged pattern on the subscriber side. I don't want to do this:
private void ValueChanged(string propertyName)
{
switch(propertyName)
{
case "Prop1":
_prop1 = _valueChangedPublisher.Prop1;
break;
case "Prop2":
_prop2 = _valueChangedPublisher.Prop2;
break;
// the more properties that are added to the publisher, the more cases I
// have to handle here :/ I don't want to have to do it this way
}
}
.NET provides the INotifyPropertyChanged interface. Inherit and implement it:
public class ValueChangedPublisher : INotifyPropertyChanged
{
private int _prop1;
private string _prop2;
public event PropertyChangedEventHandler ValueChangedHandler;
private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
public int Prop1
{
get { return _prop1; }
set
{
if (_prop1 != value)
{
_prop1 = value;
NotifyPropertyChanged();
}
}
}
public string Prop2
{
get { return _prop2; }
set
{
if (_prop2 != value)
{
_prop2 = value;
NotifyPropertyChanged();
}
}
}
}
Here is what I did to solve my problem. It's a bit large, so maybe not performant, but works for me.
Edit
See this question for performance details: C# using properties with value types with Delegate.CreateDelegate
Base Class for publishing property change stuff:
public abstract class PropertyChangePublisherBase : INotifyPropertyChanged
{
private Dictionary<string, PropertyInfo> _properties;
private bool _cacheProperties;
public bool CacheProperties
{
get { return _cacheProperties; }
set
{
_cacheProperties = value;
if (_cacheProperties && _properties == null)
_properties = new Dictionary<string, PropertyInfo>();
}
}
protected PropertyChangePublisherBase(bool cacheProperties)
{
CacheProperties = cacheProperties;
}
public bool ContainsBinding(PropertyChangedEventHandler handler)
{
if (PropertyChanged == null)
return false;
return PropertyChanged.GetInvocationList().Contains(handler);
}
public object GetPropertValue(string propertyName)
{
if (String.IsNullOrEmpty(propertyName) || String.IsNullOrWhiteSpace(propertyName))
throw new ArgumentException("Argument must be the name of a property of the current instance.", "propertyName");
return ProcessGetPropertyValue(propertyName);
}
protected virtual object ProcessGetPropertyValue(string propertyName)
{
if (_cacheProperties)
{
if (_properties.ContainsKey(propertyName))
{
return _properties[propertyName].GetValue(this, null);
}
else
{
var property = GetType().GetProperty(propertyName);
_properties.Add(propertyName, property);
return property.GetValue(this, null);
}
}
else
{
var property = GetType().GetProperty(propertyName);
return property.GetValue(this, null);
}
}
#region INotifyPropertyChanged Implementation
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void RaisePropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
handler(this, new PropertyChangedEventArgs(propertyName));
}
#endregion
}
Base Class for receiving property change stuff:
public abstract class PropertyChangeSubscriberBase
{
protected readonly string _propertyName;
protected virtual object Value { get; set; }
protected PropertyChangeSubscriberBase(string propertyName, PropertyChangePublisherBase bindingPublisher)
{
_propertyName = propertyName;
AddBinding(propertyName, this, bindingPublisher);
}
~PropertyChangeSubscriberBase()
{
RemoveBinding(_propertyName);
}
public void Unbind()
{
RemoveBinding(_propertyName);
}
#region Static Fields
private static List<string> _bindingNames = new List<string>();
private static List<PropertyChangeSubscriberBase> _subscribers = new List<PropertyChangeSubscriberBase>();
private static List<PropertyChangePublisherBase> _publishers = new List<PropertyChangePublisherBase>();
#endregion
#region Static Methods
private static void PropertyChanged(object sender, PropertyChangedEventArgs args)
{
string propertyName = args.PropertyName;
if (_bindingNames.Contains(propertyName))
{
int i = _bindingNames.IndexOf(propertyName);
var publisher = _publishers[i];
var subscriber = _subscribers[i];
subscriber.Value = publisher.GetPropertValue(propertyName);
}
}
public static void AddBinding(string propertyName, PropertyChangeSubscriberBase subscriber, PropertyChangePublisherBase publisher)
{
if (!_bindingNames.Contains(propertyName))
{
_bindingNames.Add(propertyName);
_publishers.Add(publisher);
_subscribers.Add(subscriber);
if (!publisher.ContainsBinding(PropertyChanged))
publisher.PropertyChanged += PropertyChanged;
}
}
public static void RemoveBinding(string propertyName)
{
if (_bindingNames.Contains(propertyName))
{
int i = _bindingNames.IndexOf(propertyName);
var publisher = _publishers[i];
_bindingNames.RemoveAt(i);
_publishers.RemoveAt(i);
_subscribers.RemoveAt(i);
if (!_publishers.Contains(publisher))
publisher.PropertyChanged -= PropertyChanged;
}
}
#endregion
}
Actual class to use for subscribing to property change stuff:
public sealed class PropertyChangeSubscriber<T> : PropertyChangeSubscriberBase
{
private PropertyChangePublisherBase _publisher;
public new T Value
{
get
{
if (base.Value == null)
return default(T);
if (base.Value.GetType() != typeof(T))
throw new InvalidOperationException(String.Format("Property {0} on object of type {1} does not match the type Generic type specified {2}.", _propertyName, _publisher.GetType(), typeof(T)));
return (T)base.Value;
}
set { base.Value = value; }
}
public PropertyChangeSubscriber(string propertyName, PropertyChangePublisherBase bindingPublisher)
: base(propertyName, bindingPublisher)
{
_publisher = bindingPublisher;
}
}
Here is an example of the Class with properties that you wish to be notified about:
public class ExamplePublisher: PropertyChangedPublisherBase
{
private string _id;
private bool _testBool;
public string Id
{
get { return _id; }
set
{
if (value == _id) return;
_id = value;
RaisePropertyChanged("Id");
}
}
public bool TestBool
{
get { return _testBool; }
set
{
if (value.Equals(_testBool)) return;
_testBool = value;
RaisePropertyChanged("TestBool");
}
}
}
Here is an example of the Class that will be notified when the properties in the class above change:
public class ExampleReceiver
{
public PropertyChangeSubscriber<string> Id { get; set; }
public PropertyChangeSubscriber<bool> TestBool { get; set; }
public MyExampleClass(PropertyChangePublisherBase publisher)
{
Id = new PropertyChangeSubscriber<string>("Id", publisher);
TestBool = new PropertyChangeSubscriber<bool>("TestBool", publisher);
}
}

Collection changed event for child property

I have use the following code snippet for Creating ObservableCollection binded to the DataGrid.
public class Test:INotifyPropertyChanged
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value;OnpropertyChanged("Name"); }
}
private string _city;
public string City
{
get { return _city; }
set
{
_city = value;OnpropertyChanged("City");}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
public void OnpropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
#endregion
}
class Data:INotifyPropertyChanged
{
private int customerID;
public int CustomerID
{
get { return customerID; }
set { customerID = value; OnpropertyChanged("CustomerID"); }
}
private bool isSelected;
public bool IsSelected
{
get { return isSelected; }
set { isSelected = value; OnpropertyChanged("IsSelected"); }
}
private ObservableCollection<Test> _collection;
public ObservableCollection<Test> Collection
{
get { return _collection; }
set { _collection = value;OnpropertyChanged("Collection" +
""); }
}
public event PropertyChangedEventHandler PropertyChanged;
public void OnpropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null)
{
var e = new PropertyChangedEventArgs(propertyName);
handler(this, e);
}
}
}
class ViewModel:NotificationObject
{
public ViewModel()
{
this.GDCSource = Getsource();
}
private ObservableCollection<Data> _gdcsource;
public ObservableCollection<Data> GDCSource
{
get { return _gdcsource; }
set { _gdcsource = value; RaisePropertyChanged("GDCSource");}
}
private ObservableCollection<Data> Getsource()
{
ObservableCollection<Data> items = new ObservableCollection<Data>();
if (items != null)
{
items.Add(new Data()
{
IsSelected = true,
CustomerID = 1,
});
items.Add(new Data()
{
IsSelected = true,
CustomerID = 2,
});
}
return items;
}
}
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
ViewModel vmModel = new ViewModel();
this.datagrid.ItemsSource = vmModel.GDCSource;
vmModel.GDCSource.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(GDCSource_CollectionChanged);
}
void GDCSource_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
//Listen the collection changed event for underlying source
}
// add the object to the Collection property
private void Test_OnClick(object sender, RoutedEventArgs e)
{
(this.DataContext as ViewModel).GDCSource[0].Collection.Add(new Test() { Name = "Name1", City = "City1" });
(this.DataContext as ViewModel).GDCSource[0].Collection.Add(new Test() { Name = "Name1", City = "City1" });
(this.DataContext as ViewModel).GDCSource[0].Collection.Add(new Test() { Name = "Name1", City = "City1" });
}
}
It is possible to listen while adding Collection property in any event.
Thanks in advance
Regards,
Rajasekar
If you mean you want to register for event that is raised when item is added/deleted in observable collection you should look at CollectionChanged event
ObservableCollection<T>.CollectionChanged Event
Occurs when an item is added, removed, changed, moved, or the entire
list is refreshed.
You can extend your own version of ObservableCollection if you want and override the add method,
There you can fire any delegates or whatever you may want to register, the UI will update automatically using ObservableCollection with items added/removed you don't need to do anything for that,

Categories

Resources