In a code behind XAML file, if my DataContext will always be a well-known class, i usually redeclare DataContext like this:
public new Cow DataContext
{
get { return base.DataContext as Cow; }
set { base.DataContext = value; }
}
This way i have Intellisense treating DataContext as a Cow in the scope of my file and I am safely (at least i think so) using the base.DataContext to handle all its logic.
Some people, with lots of experience, have already told me that this is not a good pattern.
I’d like to know what problems could arise and why not use it. I’ve already given it a lot of thought and couldn’t think of one
Thank you
After pondering for a while about that code I cannot find any serious issue, except perhaps for this corner case that I will explain.
Let’s say your Xaml belongs to a class called MyUserControl, and that it inherits from UserControl.
Let’s assume you have:
This is obviously legal and you are not protected by MyUserControl’s type-safety, because the type of the reference variable is of UserControl, whose DataContext property is still of object type. However, let’s immagine down the line, you try the following, in MyUserControl’s context:
c will be null. This is what you intended. However, it might make your life harder under a debugging scenario because you are being lulled into thinking your DataContext is null, while it simply isn’t what you expected it to be. It might be harder to understand why your data bindings are all working funny while your datacontext seems to be null.
My approach to this is not to hide the DataContext property, but to re-expose it via a new property:
In the scenario I set up above, while the Model property would return null, the DataContext would return a reference to the Dog instance, more appropriately reflecting what is really going on. Alternatively, you might implement your DataContext property’s getter by returning the following:
At least you’d receive an exception telling you DataContext does have something, but not what you want. It does seem cheesy, however.
Anyhow, this is really no serious issue, only a possible inconvenience under the scenario I laid out.