当我提供默认值时,为什么依赖属性实现会导致我的应用程序崩溃?
这段代码位于我的UserControl对象的类声明中。一切都正常 - 它编译并运行得非常完美。
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); }
}
然而,当我给依赖属性添加默认值时:代码可以编译,但在尝试实例化用户控件时会崩溃并抛出致命异常。
供参考,现在我的代码看起来像这样 - 添加了PropertyMetaData行:
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); }
}
从调用Register()中删除PropertyMetadata可以使程序完美地运行,没有任何崩溃或其他问题。但是我需要默认值以供后续代码使用。如何在不崩溃的情况下接受默认值?
当它崩溃时,输出窗口显示以下异常:
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
我需要尽快让这个工作起来,所以任何建议都将非常棒!