wpf – 当我提供默认值时,为什么依赖项属性实现会破坏我的应用程
当我提供默认值时,为什么依赖项属性实现会使我的应用程序崩溃?
这段代码位于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(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 我需要尽快开始工作,所以任何建议都会很棒!
简短回答:
依赖属性默认值需要是线程安全的(例如从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在每次抛出的异常中都会中断是非常有帮助的.只需转到“调试” – > “异常”并检查“公共语言运行时异常”“抛出”. 然后,系统会提示您并获取异常消息,在您的情况下如下所示:“附加信息:’Rect’属性的默认值不能绑定到特定线程.” (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |