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

8

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

这段代码位于我的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  

我需要尽快让这个工作起来,所以任何建议都将非常棒!


如果你有一个堆栈跟踪,那将非常有帮助。 - Anderson Imes
真的吗?我不知道那是相关的。让我看看我能想出什么……可能要等一会儿才能开始——现在正忙于一些紧急的事情。 - Giffyguy
1个回答

19

简短回答:

依赖属性默认值需要线程安全(例如从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在每次抛出异常时中断真的非常有帮助。只需转到“调试”->“异常”,然后选中“公共语言运行时异常”“已抛出”。

然后,您将收到异常消息,其中在您的情况下看起来像这样:“Additional information: Default value for the 'Rect' property cannot be bound to a specific thread.”


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接