WPF – order is matter (especially with DependencyProperty)
What’s wrong with following code:
class aaa : DependencyObject { }
class bbb : DependencyObject
{
static readonly bbb b = new bbb();
public static bbb GetMe { get { return b; } }public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(aaa), typeof(bbb), new UIPropertyMetadata(default(aaa)));private bbb()
{
MyProperty = new aaa();
}
public aaa MyProperty
{
get { return (aaa)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
}
Nothing special, One DependencyObject, that implement singleton pattern. You should call GetMe to create and get an instance and then use it.
Well, this code throws "Value cannot be null. Parameter name: dp" exception. Why this happens? Why class aaa can not be null? It can – it dependency object!
How to fix it? Just move registration of DependencyPropery above initialization of static bbb to solve it. Like this
class aaa : DependencyObject { }
class bbb : DependencyObject
{
public static readonly DependencyProperty MyPropertyProperty =
DependencyProperty.Register("MyProperty", typeof(aaa), typeof(bbb), new UIPropertyMetadata(default(aaa)));static readonly bbb b = new bbb();
public static bbb GetMe { get { return b; } }private bbb()
{
MyProperty = new aaa();
}
public aaa MyProperty
{
get { return (aaa)GetValue(MyPropertyProperty); }
set { SetValue(MyPropertyProperty, value); }
}
}
Why this happens? Well, even compiled, WPF initializes static classes by using it’s order in code. Don’t believe me? Open ILDasm for evidences.
Conclusion – I think, it should be reported as bug, however, from the other hand, it makes sense. You choose what’s right and what’s wrong.
Great thank to Kael and Matthew for helping me to debug it.
You may also be interested with:
December 4th, 2007 · Comments (1)
One Response to “WPF – order is matter (especially with DependencyProperty)”
Leave a Reply
Discover other tags
My tools
- .NET Framework Detector
- Duplicate images finder
- Exchange Security Policy for Windows Mobile Devices Fix
- Gas Price Windows Vista SideBar gadget
- Israel Traffic Information Windows Vista SideBar gadget
- Localization fix for SAP ES Explorer for Visual Studio
- LocTester
- RTL and LTR in Windows Live Writer
- Silverlight controls library
- Snipping tool integration plugin for WLW
- USB FM receiver library
- Vista Battery Saver
- WebCam control for WPF
- Windows Live SkyDrive attachment for Windows Live Writer
- Wireless Migrator
- WPF Virtual Keyboard





January 1st, 2009 at 12:31 am
What's wrong with following code: class aaa : DependencyObject { } class bbb : DependencyObject