当我提供默认值时,为什么依赖项属性实现会使我的应用程序崩溃?
这段代码位于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); }
}
Run Code Online (Sandbox Code Playgroud)
但是,当我将缺省值添加到依赖项属性时:
代码编译,但在尝试实例化UserControl时崩溃并发生致命异常.
作为参考,我的代码现在看起来像这样 - 添加了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); }
}
Run Code Online (Sandbox Code Playgroud)
从调用Register()中删除PropertyMetadata会导致程序完美运行,不会出现任何崩溃或任何其他问题.但我需要以后代码的默认值.如何在不崩溃的情况下让它接受默认值?
当它崩溃时,输出窗口中会显示以下异常:
A first chance exception of type 'System.ArgumentException' occurred in WindowsBase.dll
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred …Run Code Online (Sandbox Code Playgroud)