I have a static class that models a telephone exchange which instantiates Phone Objects in their own individual windows; the exchange maintains a list of the Phones instantiated and I need a way to “dial” from one phone object into another – For example if I created two phone objects and entered the second phones number into a text box on the first I’d like a property on the second phone to be updated with the first phone (callers) number
I’ve done data binding but I’m new to INotifyPropertyChanged, here’s what I have:
Phone class:
public class Phone : INotifyPropertyChanged
{
private string _receivedNumber;
public Phone(string phoneNumber)
{
PhoneNumber = phoneNumber;
}
public string PhoneNumber
{
get;
set;
}
public string Status
{
get;
set;
}
public string ReceivedNumber
{
get { return _receivedNumber; }
set
{
_receivedNumber = value;
OnPropertyChanged("ReceivedNumber");
}
}
private void OnPropertyChanged(string receivedNumber)
{
if (PropertyChanged !=null)
{
PropertyChanged(this, new PropertyChangedEventArgs(receivedNumber));
}
}
public event PropertyChangedEventHandler PropertyChanged;
}
}
Here is the logic in my PhoneWindow.xaml.cs, once the call button is clicked on the first phone the phone it wants to connect to is assigned to the Phone object (receiver) from my Exchange list (if it exists) – By now the two objects are instantiated and both displaying in their own windows.
I set the second phone ReceivedNumber property to the caller and here’s where I’m unsure, how do I update the binding/context to reflect the caller number on the second Phone object?
private void BtnCallClick(object sender, RoutedEventArgs e)
{
string number = txtDialNumber.Text;
if (String.IsNullOrEmpty(number) || !IsNumeric.IsValidNumber(number) || Exchange.RetrievePhone(number) == null)
{
MessageBox.Show("The number entered is not valid or the phone doesn't exist");
return;
}
Phone receiver = Exchange.RetrievePhone(number);
receiver.ReceivedNumber = _phone.PhoneNumber;
receiver.PropertyChanged += //<-- How to implement this?
}
Many thanks
I wrote a ModelBase Abstract Class for MVVM models that allows the ability to subscribe to properties.
You can find that here:
http://xcalibur37.wordpress.com/2012/02/06/creating-a-viewmodel-base-part-iii-subscribing-can-make-all-the-difference/
It would work like this:
So, if 2 different ViewModels subscribed to myModel.MeterReading, they could both receive updates if the property is changed.