Creating Collections in XAML – Silverlight the Missing Notes

(This is a series of unspoken Silverlight best practices, designed to avoid specific pain points when developing Silverlight applications. Refer to this URL http://www.redmountainsw.com/wordpress/?p=1270#list for a complete listing).

Read the following if you’d like to be able to see your results before you develop the back end services for it.

I wanted a Facebook-like comment control for a project, one that looks like the following:

and my class looks like this:

public class Comment
{
  public string Name {get; set;}
  public string CommentText {get; set; }
  public IEnumerable<Comment> Replies {get; set;}
}

However, when I try to create this in XAML, it failed to databind properly. Furthermore, I get errors when running the project.

<local:Comment Name="Kathy Parkes" CommentText="Can anybody recommend a prototyping tool?">
  <local:Comment.Replies>
    <local:Comment Name="Marcus Value" CommentText="Have you tried Axure?" />
    <local:Comment Name="Kathy Parkes" CommentText="It is too expensive." />
    <local:Comment Name="John Coates" CommentText="How about using powerpoint?" />
  </local:Comment.Replies>
</local:Comment>

The solution is to create custom collection types see reference http://msdn.microsoft.com/en-us/library/cc645020(v=vs.95).aspx#Collection_Properties

public class Comment
{
  public string Name {get; set;}
  public string CommentText {get; set; }
  public CommentCollection Replies {get; set;} 

  public Comment()
  {
    this.Replies = new CommentCollection();
  }
}

// This is the trick!
public class CommentCollection: IList<Comment>

About this entry