Friday, March 29, 2013

ChangeAwareContentControl–How to know when the content changes in a ContentControl

I am working on an application where I have a ContentControl, and I need to know when the content changes. My initial thought was to add an event handler for the ContentChanged event. I came to find out that the ContentControl does not fire a ContentChanged event.

My solution was to create a control derived from content control that fires that particular event. It is working quite nicely, so I thought I would share. I hope it helps you out. It’s a small amount of code, but it does the trick.

    public class ChangeAwareContentControl : ContentControl
{
static ChangeAwareContentControl()
{
ContentProperty.OverrideMetadata(
typeof(ChangeAwareContentControl),
new FrameworkPropertyMetadata(
new PropertyChangedCallback(OnContentChanged)));
}

private static void OnContentChanged(DependencyObject d,
DependencyPropertyChangedEventArgs e)
{
ChangeAwareContentControl mcc = d as ChangeAwareContentControl;
if (mcc.ContentChanged != null)
{
DependencyPropertyChangedEventArgs args
=
new DependencyPropertyChangedEventArgs(
ContentProperty, e.OldValue, e.NewValue);
mcc.ContentChanged(mcc, args);
}
}

public event DependencyPropertyChangedEventHandler ContentChanged;
}


Here is how you use it in xaml.



<controls:ChangeAwareContentControl ContentChanged="ContenChangedHandler"/>


1 comment:

  1. Very nice. It works like a charm. Thanks for sharing (though it's stupid that WPF doesnot provide ContentChanged event by default)

    ReplyDelete