Click here to Skip to main content
14,769,456 members
Articles » Web Development » Silverlight » Controls
Technical Blog
Posted 28 Jul 2009

Stats

385.4K views
6 bookmarked

Silverlight DataContext Changed Event

Rate me:
Please Sign up or sign in to vote.
4.43/5 (6 votes)
28 Jul 2009CPOL
One known issue with Silverlight is that the DataContext bound to a control may change, but there is no readily available change event. Unlike WPF, you don't have an explicit event to register with in order to track changes.

One known issue with Silverlight is that the DataContext bound to a control may change, but there is no readily available change event. Unlike WPF, you don't have an explicit event to register with in order to track changes. This becomes a problem in controls like the DataGrid control which reuses the same control instances for each page. Even though fresh data is bound, if your control isn't aware that the data context changed, it will keep stale content.

If you search online you'll find the solution is simple: you create a dependency property that is actually based on the data context (call it a "dummy" property) and then register for changes to that property. I was glad to find the solution but wanted something a little more reusable (remember, I like the DRY principle: don't repeat yourself, so when I find myself writing the same line of code more than once I have to go back and refactor).

The solution? I was able to find something that I think works well and involves an interface and a static class.

First, I want to identify when a control should be aware of changes to DataContext and also provide a method to call when this happens. That was easy enough. I created IDataContextChangedHandler and defined it like this:

public interface IDataContextChangedHandler<T> where T: FrameworkElement 
{
   void DataContextChanged(T sender, DependencyPropertyChangedEventArgs e);
}

As you can see, it is a simple interface. A method is called with the sender (which will presumably be the control itself) and the arguments for a dependency property changed event. It is typed to T, of course.

Next, I used generics to create a base class that manages the "fake" dependency property:

public static class DataContextChangedHelper<T> where T: FrameworkElement, IDataContextChangedHandler<T>
{
    private const string INTERNAL_CONTEXT = "InternalDataContext"; 

    public static readonly DependencyProperty InternalDataContextProperty =
        DependencyProperty.Register(INTERNAL_CONTEXT,
                                    typeof(Object),
                                    typeof(T),
                                    new PropertyMetadata(_DataContextChanged));

    private static void _DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        T control = (T)sender;
        control.DataContextChanged(control, e);
    }

    public static void Bind(T control)
    {
        control.SetBinding(InternalDataContextProperty, new Binding());
    }
}

As you can see, the class does a few things and works for any framework element, which is a "basic building block" that supports binding. It is typed to the FrameworkElement but also requires that the target implements IDataContextChangedHandler. It creates a dependency property. Because the data context can be any object, the type of the dependency is object, but the type of the parent is the framework element itself ("T"). When something happens to the property, it will invoke _DataContextChanged.

The event handler is sent the control that raised the event as well as the arguments for the old and new properties in the data context. We simply cast the sender back to its original type of T. Then, because we know it implements IDataContextChangedHandler, we can simply call DataContextChanged.

Finally, there is a static call to bind the control itself.

Now let's put the pieces together. Let's say you have a control that makes a gauge based on a data value, and you want to put the control in the grid. You need to know when the DataContext changes, because you will update your gauge. The control will look like this:

public partial class Gauge : IDataContextChangedHandler<Gauge> 
{
   public Gauge() 
   {
      InitializeComponent();
      DataContextChangedHelper<Gauge>.Bind(this); 
   }

   public void DataContextChanged(Gauge sender, DependencyPropertyChangedEventArgs e)
   {
      if (e.NewValue != null)
      {
         int gaugeLevel = (int)e.NewLevel;
         _UpdateImage(gaugeLevel);
      } 
   }
}

And there you have it - to register for the data context changing, we simply implemented IDataContextChangedHandler and then registered by calling Bind in our constructor.

Jeremy Likness

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Jeremy Likness
Program Manager Microsoft
United States United States
Note: articles posted here are independently written and do not represent endorsements nor reflect the views of my employer.

I am a Program Manager for .NET Data at Microsoft. I have been building enterprise software with a focus on line of business web applications for more than two decades. I'm the author of several (now historical) technical books including Designing Silverlight Business Applications and Programming the Windows Runtime by Example. I use the Silverlight book everyday! It props up my monitor to the correct ergonomic height. I have delivered hundreds of technical presentations in dozens of countries around the world and love mentoring other developers. I am co-host of the Microsoft Channel 9 "On .NET" show. In my free time, I maintain a 95% plant-based diet, exercise regularly, hike in the Cascades and thrash Beat Saber levels.

I was diagnosed with young onset Parkinson's Disease in February of 2020. I maintain a blog about my personal journey with the disease at https://strengthwithparkinsons.com/.


Comments and Discussions

 
QuestionI'm getting an error when the event is raised ? Pin
ShultzT7-Jul-14 11:04
MemberShultzT7-Jul-14 11:04 
QuestionCannot access value in DataContextChanged event Pin
mac4_life17-Jan-12 7:48
Membermac4_life17-Jan-12 7:48 
GeneralMy vote of 5 Pin
SpazMoose11-May-11 11:07
MemberSpazMoose11-May-11 11:07 
GeneralA more generic solution Pin
zlezj16-Jun-10 2:39
Memberzlezj16-Jun-10 2:39 
General错误 1 不能将类型“Gauge”用作泛型类型或方法“IDataContextChangedHandler<t>”中的类型形参“T</t> Pin
tjmxf10-Jan-10 23:41
Membertjmxf10-Jan-10 23:41 
Generalbinding() cannot find namespace Pin
tjmxf10-Jan-10 23:20
Membertjmxf10-Jan-10 23:20 
GeneralRe: binding() cannot find namespace Pin
Jeremy Likness11-Jan-10 2:05
professionalJeremy Likness11-Jan-10 2:05 
GeneralRe: binding() cannot find namespace Pin
tjmxf11-Jan-10 15:24
Membertjmxf11-Jan-10 15:24 
GeneralRe: binding() cannot find namespace Pin
tjmxf11-Jan-10 15:27
Membertjmxf11-Jan-10 15:27 
GeneralReally "simple" solution Pin
Lauren Lilly4-Aug-09 6:14
MemberLauren Lilly4-Aug-09 6:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.