Is there any feature of c# (silverlight) in which I can watch a property of a usercontrol for when there is any changes made without using dependency properties? I want one that is not static.
+1
A:
There are two standard mechanisms where the "observation" pattern (which is what are describing) is implement. One is the use of dependency properties.
The other is the implementation of the INotifyPropertyChanged interface.
public partial class MyUserControl : UserControl, INotifyPropertyChanged
{
string _myProperty;
public string MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
private void NotifyPropertyChanged(string name)
{
if (PropertyChanged != null)
PropertyChanged(this, new PropertyChangedEventArgs(name);
}
public event PropertyChangedEventHandler PropertyChanged
}
In order to watch a property you need to attach to the PropertyChanged
event.
MyUserControl control = new MyUserControl();
control += Control_PropertyChanged;
...
void Control_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == "MyProperty")
{
//Take appropriate action when MyProperty has changed.
}
}
AnthonyWJones
2010-02-21 18:41:56