views:

72

answers:

1

I want to set a default value of my Attached Property, but when I do I get:

A first chance exception of type 'System.ArgumentException' occurred in WindowsBase.dll

A first chance exception of type 'System.TypeInitializationException' occurred in Oef_AttDepProp.exe

Without the default value, things work fine. This is some sample code I used:

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();
}

It's the "new clsPersoon("test", "test")" which seems to be the cause the problem, but that is only a very simple class with a 2-string-constructor.

Edit: When trying to set the property through a click event, instead of the window_load, I get an innerException of: "Default value for the 'Eigenaar' property cannot be bound to a specific thread."

A: 

Typically exceptions of type TypeInitializationException are thrown when an exception occurs in the static constructor. Look there.

Also, from the inner exception:

Default value for the Eigenaar property cannot be bound to a specific thread.

This usually means that your property is not thread-safe (e.g., doesn't inherit from System.Windows.Freezable). Check this thread for gory details and MSDN for details about default values for dependency properties.

Jason
Indeed, with the new inner exception I found the same thing (at first I didn't get that inner exception, because I set the value in window_load).When I inherit from Freezable, I'm not able any more to inherit from DependencyObject in my clsPersoon class though... Do I have to chose now, which one to use, and does losing the DependencyObject have any downsides?
Avalon
@Avalon: `Freezable` inherits from `DependencyObject`.
Jason
Ow, I see, didn't think that far through, mea culpa.Thanks, to the both of you!
Avalon