附加属性:设置默认值时的'System.TypeInitializationException'

时间:2010-01-20 14:28:58

标签: c# wpf attached-properties argumentexception

我想设置我的附属财产的默认值,但是当我这样做时,我得到:

  

WindowsBase.dll中出现'System.ArgumentException'类型的第一次机会异常

     

Oef_AttDepProp.exe中出现'System.TypeInitializationException'类型的第一次机会异常

没有默认值,一切正常。 这是我使用的一些示例代码:

public static readonly DependencyProperty IsEigenaarProperty = DependencyProperty.RegisterAttached(
"Eigenaar", typeof(clsPersoon), typeof(UIElement), 
new UIPropertyMetadata(new clsPersoon("test", "test"), PropertyChanged));

[DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)]
[Browsable(true)]
public clsPersoon Eigenaar
{
 get
 {
  return _persoon;
 }
 set
 {
  _persoon = value;
 }
}

public static void SetEigenaar(UIElement element, clsPersoon value)
{
 element.SetValue(IsEigenaarProperty, value);
}

public static clsPersoon GetEigenaar(UIElement element)
{
 return (clsPersoon)element.GetValue(IsEigenaarProperty);
}

private static void PropertyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
 if (obj is Window1)
  ((Window1)obj).Title = GetEigenaar(((Window1)obj)).ToString();
}

这是“新的clsPersoon(”测试“,”测试“)”,这似乎是问题的原因,但这只是一个非常简单的类,带有2个字符串的构造函数。

编辑:当尝试通过click事件而不是window_load设置属性时,我得到一个innerException:“'Eigenaar'属​​性的默认值不能绑定到特定的线程。“

1 个答案:

答案 0 :(得分:2)

当静态构造函数中发生异常时,通常会抛出类型TypeInitializationException的异常。看那里。

另外,从内部异常:

  

Eigenaar属性的默认值不能绑定到特定线程。

这通常意味着您的属性不是线程安全的(例如,不继承自System.Windows.Freezable)。有关详细信息,请查看此thread,有关依赖项属性的默认值的详细信息,请查看MSDN

相关问题