Silverlight 4 - Declare / populate a management collection property via XAML?

First of all, I would like to thank all of you for all the wonderful materials that you have provided. I have to admit that StackOverflow was the biggest tutor resource, and as such, it provided me with more knowledge than ... 4 years at college. Thanks!

I am working with a control that has a property that is a collection of objects.

public class UserParameter { string DisplayName { get; set; } string Property { get; set; } string Type { get; set; } } public class ParameterBuilder: UserControl { private ObservableCollection<UserParameter> parameters; //alright - this is really dependency property. //described as property just for simplicity. public ObservableCollection<UserParamter> Parameters { get { return this.parameters; } set { this.parameters = value; } } } 

So, the meat of this question is figuring out how to create this collection in Xaml. For instance:

 <custom:ParameterBuilder Name="Parameter"> <custom:ParameterBuilder.Parameters> <custom:UserParameter DisplayName="Test 0" Property="Size" Type="String"/> <custom:UserParameter DisplayName="Test 1" Property="Value" Type="Decimal"/> </custom:ParameterBuilder.Parameters> </custom:ParameterBuilder> 

Is this possible, and if so, how can I do this?

+4
source share
2 answers

In general, collection properties should be simple, old (independent) read-only properties. The XAML parser is smart enough to add elements to collection properties. For instance:

 public class ParameterBuilder: UserControl { private ObservableCollection<UserParameter> parameters = new ObservableCollection<UserParameter>(); // Don't make it a dependency property public ObservableCollection<UserParamter> Parameters { get { return this.parameters; } } } 

And you can use it as described:

 <custom:ParameterBuilder Name="Parameter"> <custom:ParameterBuilder.Parameters> <custom:UserParameter DisplayName="Test 0" Property="Size" Type="String"/> <custom:UserParameter DisplayName="Test 1" Property="Value" Type="Decimal"/> </custom:ParameterBuilder.Parameters> </custom:ParameterBuilder> 
+1
source

If you are using .NET 4.0, you should be able to reference generic files with the x: TypeArguments parameter ( part of the XAML2009 specification ) so the Observable Collection in your argument will be declared as follows:

 <ObservableCollection x:TypeArguments="UserParameter"> <l:UserParameter DisplayName="Test 0" Property="Size" Type="String" /> <l:UserParameter DisplayName="Test 1" Property="Value" Type="Decimal" /> </ObservableCollection /> 
+2
source

All Articles