Event for reference variable assigned to new instance?
Is there any design pattern or proper way to notify an Object A ,which
references an instance of an Object B through a reference variable B b =
new B(); A = b;, that the reference variable is referencing something
else\new? b = new B(); The reason I am asking is because this becomes
relevant to me when Object B contains data that is used for data binding.
I included some more explicit code to show my intent.
public class Person : INotifyPropertyChanged
{
//Fields
private string _name;
private int _age;
//Properties
public string Name { get { return _name; } set { if (Name != value) {
_name = value; OnPropertyChanged("Name"); } } }
public int Age { get { return _age; } set { if (Age != value) { _age =
value; OnPropertyChanged("Age"); } } }
//Events
public event PropertyChangedEventHandler PropertyChanged;
//Event-related Methods
protected void OnPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
//Constructors
public Person()
{
Name = "Default";
Age = 0;
}
public Person(string name, int age)
{
this.Name = name;
this.Age = age;
}
}
public partial class MainWindow : Window
{
private ObservableCollection<Person> people;
public MainWindow()
{
people = new ObservableCollection<Person>();
people.Add(new Person { Name = "Scott", Age = 23 });
people.Add(new Person { Name = "Joe", Age = 40 });
dataGrid1.ItemsSource = people;
InitializeComponent();
}
//Change a name in the person collection
private void btnChangeName_Click(object sender, RoutedEventArgs e)
{
if (people.Count > 0)
{
people.First().Name = "Name Changed";
}
}
//Add a name in the person collection
private void btnAddName_Click(object sender, RoutedEventArgs e)
{
people.Add(new Person { Name = "New Guy", Age = 18 });
}
//Change 'people' to a new person collection
private void btnChangeCollection_Click(object sender, RoutedEventArgs e)
{
people = new ObservableCollection<Person>();
people.Add(new Person { Name = "Pinky", Age = 24 });
people.Add(new Person { Name = "Brain", Age = 65 });
//The follow line must be in place for this to work
dataGrid1.ItemsSource = people;
}
}
If I change any data within the object such as the Name, it will reflect
properly to an object that is data bound to it. However if I reassign
people, then the object that is databound to people will not receive the
new reference unless I explicitly tell it to. My main question would be
what would be the proper way to setup an event that triggers whenever
people references a different object?
No comments:
Post a Comment