views:

32

answers:

1

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?

+3  A: 

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; }
}
Curt Nichols
Thanks for the info. So is there no way to do this in XAML? I was trying to avoid code-behind. This was mostly a thought-experiment to practice XAML as opposed to an actual production problem.
jkohlhepp
All I've done is modify your TextItemCollection class to work correctly. Swap my TextItemCollection for yours and your resource markup should work. I'm not suggesting that you do it in code behind; you don't need to.
Curt Nichols
Gotcha. I see what you're saying now. Unfortunately I've completely moved past that example so I can no longer recreate the problem. But I'll give you the credit for the answer since this was probably it.
jkohlhepp