当我提供默认值时,为什么依赖项属性实现会破坏我的应用程序?

Gif*_*guy 7 wpf dependency-properties exception .net-3.5

当我提供默认值时,为什么依赖项属性实现会使我的应用程序崩溃?

这段代码位于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 in mscorlib.dll  
A first chance exception of type 'System.Windows.Markup.XamlParseException' occurred in PresentationFramework.dll  
Run Code Online (Sandbox Code Playgroud)

我需要尽快完成这项工作,所以任何建议都会很棒!

Chr*_*rkl 17

简短回答:

依赖属性默认值需要是线程安全的(例如从System.Windows.Freezable继承),但System.Windows.Forms.Rectangle不是.

答案很长:

http://social.msdn.microsoft.com/forums/en-US/wpf/thread/2cb12481-ef86-40b7-8333-443598d89933/

暗示:

如果您使用的是Visual Studio,那么让IDE在每次抛出的异常中都会中断是非常有帮助的.只需转到"Debug" - >"Exceptions"并选中"Common Language Runtime Exceptions""Thrown".

然后,系统会提示您并获取异常消息,在您的情况下如下所示:"附加信息:'Rect'属性的默认值不能绑定到特定线程."