This post shows how you can create property changed event if such event is missing from base class.
When you need property change event for some property defined inside a base class library you may try this trick. This is specific for Silverlight and uses template bindings.
Let's consider e.g. Silverlight Control class. When you create any custom control you may need to know when Control class properties are changed.
Control class has several font related properties, however there is no property changed event for any of those properties.
If you need to get event when e.g. FontSize property is changed you can use the following trick:
Create special purpose control which will define property changed event:
public class MyEventControl : Control
{
public static readonly DependencyProperty FontSizeSourceProperty =
DependencyProperty.Register("FontSizeSource", typeof(double), typeof(MyEventControl),
new PropertyMetadata(new PropertyChangedCallback(OnPropertyChanged)));
public MyEventControl()
{
}
static void OnPropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
{
(obj as MyEventControl).OnPropertyChanged(e);
}
void OnPropertyChanged(DependencyPropertyChangedEventArgs e)
{
if (PropertyChanged == null)
return;
PropertyChanged(this, e);
}
public double FontSizeSource
{
get { return (double)GetValue(FontSizeSourceProperty); }
set { SetValue(FontSizeSourceProperty, value); }
}
public event DependencyPropertyChangedEventHandler PropertyChanged;
}
The code above is very simple: one dependency property, which we'll use as a source, plus event.
Next you need to use this control inside style for your custom control. Style means Xaml code :)
Put it into Xaml code and bind FontSizeSource property to FontSize:
<local:MyEventControl
x:Name="eventControl"
FontSizeSource="{TemplateBinding FontSize}" />
That's it. Now you can obtain eventControl instance inside OnApplyTemplate method in your custom control and use PropertyChanged event:
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
eventControl = GetTemplateChild("eventControl") as MyEventControl;
if (eventControl != null)
eventControl.PropertyChanged += new DependencyPropertyChangedEventHandler(ehPropertyChanged);
}
Now when control's FontSize property is changed we'll get ehPropertyChanged event handler called. Thanks to template binding we used inside xaml!