Silverlight Nested Custom Controls results in StackOverflowException
12:48 09 Jun 2015

I'm writing a reusable Controllibrary for my Silverlight Projects. At the moment I get an StackOverflowException each Time I startup my test Application which is using the Controllibrary. I was able to reproduce the Exception in a small sample Project.

I have two simple Custom Controls:

//Control1.cs
public class Control1:Control
{
    public Control1()
    {
        this.DefaultStyleKey = typeof(Control1);
    }
}

//Control2.cs
public class Control2:Control
{
    public static DependencyProperty TestProperty =  
            DependencyProperty.Register("Test",typeof(Control1),typeof(Control2),null);

    public Control1 Test
    {
        get {return (Control1)GetValue(TestProperty);}
        set {SetValue(TestProperty,value);}
    }

    public Control2()
    {
        this.DefaultStyleKey = typeof(Control2);
    }
}

Constrol2 has a DependencyProperty of Type Control1. In my Controllibrary Control1 is something similar to a MenuItem which is passed to the Menu when Control2 is pressed. Now in my Themes/generic.xaml I am defining the two default Styles for the Controls:

//generic.xaml



Now when I use Control2 in a Test Application I am getting a StackOverflowException. When setting up Breakpoints the Constructor of Control2 is called once an then the Constructor of Control1 is called continuously until the StackOverflowException.

When I change Control1s constructor to load its style directly from a ResourceDictionary with a resourceKey everything loads fine. But that is more like a Workaround than a Solution.

When I remove the Setter for my TestProperty in the generic.xaml everything works fine as well. Then I am able to override the Style in my App.xaml of the Test Application and define the Setter for the TestProperty there. But that's also not what I want to do.

Does anyone have a Solution for this Problem? Or maybe an someone can explain me why it behaves that way.

Thanks in advance

c# xaml silverlight controls stack-overflow