Why would a dependency-property implementation crash my application when I provide a default value?
This segment of code is in the class declaration for my UserControl object. Everything works fine - it compiles and runs perfectly.
public static System.Windows.DependencyProperty DepProp
= System.Windows.DependencyProperty.Register( "Rect",
typeof(System.Windows.Shapes.Rectangle),
typeof(FooControl));
public System.Windows.Shapes.Rectangle Rect
{
get
{ return ((System.Windows.Shapes.Rectangle)(GetValue(DepProp))); }
set
{ SetValue(DepProp, value); }
}
However, when I add the default value to the dependency property:
The code compiles, but crashes with a fatal exception when it tries to instantiate the UserControl.
For reference, my code now looks like this - with the PropertyMetaData line added:
public static System.Windows.DependencyProperty DepProp
= System.Windows.DependencyProperty.Register( "Rect",
typeof(System.Windows.Shapes.Rectangle),
typeof(FooControl),
new System.Windows.PropertyMetadata(new System.Windows.Shapes.Rectangle()));
public System.Windows.Shapes.Rectangle Rect
{
get
{ return ((System.Windows.Shapes.Rectangle)(GetValue(DepProp))); }
set
{ SetValue(DepProp, value); }
}
Removing the PropertyMetadata from the call to Register() causes the program to function perfectly, without any crashes or any other problems. But I need the default value for later code. How can I get it to accept the default value without crashing?
When it crashes, the following exceptions are shown in the output window:
A first chance exception of type 'System.ArgumentException' occurred in WindowsBase.dll
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll
I need to get this working ASAP, so any advice would be awesome!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…