RationalGeek
RationalGeek

Reputation: 9599

Collection declared in XAML hangs Silverlight

I have been playing around with declaring objects in XAML. I have these classes in my Silverlight assembly:

public class TextItem
{
    public string TheValue { get; set; }
}

public class TextItemCollection
{
    public ObservableCollection<TextItem> TextItems { get; set; }
}

Then, I have this in my XAML:

<UserControl.Resources>
    <app:TextItemCollection x:Key="TextItemsResource">
        <app:TextItemCollection.TextItems>
            <app:TextItem TheValue="Hello world I am one of the text values"/>
            <app:TextItem TheValue="And I am another one of those text items"/>
            <app:TextItem TheValue="And I am yet a third!"/>
        </app:TextItemCollection.TextItems>
    </app:TextItemCollection>
</UserControl.Resources>

For some reason if I include that node when I try to debug the application, Silverlight hangs (I just see the spinning blue loading circle thingy). If I comment out that node, it runs immediately.

Any ideas?

Upvotes: 4

Views: 2097

Answers (1)

Curt Nichols
Curt Nichols

Reputation: 2767

By code review: Your TextItems property is null. That can't help the XAML parser.

By experimental results: I get an exception when running the app in the debugger (I'm using Silverlight 4):

System.Windows.Markup.XamlParseException occurred
  Message=Collection property '__implicit_items' is null. [Line: 12 Position: 40]
  LineNumber=12
  LinePosition=40
  StackTrace:
       at System.Windows.Application.LoadComponent(Object component, Uri resourceLocator)
  InnerException: 

You should initialize TextItems. You should also make the setter private so others can't mess you up. Try this, you should find it works fine:

public class TextItemCollection
{
    public TextItemCollection()
    {
        TextItems = new ObservableCollection<TextItem>();
    }

    public ObservableCollection<TextItem> TextItems { get; private set; }
}

Upvotes: 6

Related Questions