Silverlight 4 - Declare/Populate a control's collection property via XAML?
First of all I wanted to thank all of you for all the wonderful input you have provided. I have to admit - StackOverflow has been the greatest peer-tutor resource available, and as such it has provided me with more knowledge, than ... the 4 years in "college". Thanks!
I am working with a control that has a property which 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 to figure out how to create this collection in Xaml. For example:
<custom:ParameterBuilder Name开发者_JS百科="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 do I go about doing it?
If you are using .NET 4.0 you should be able to reference generics with the x:TypeArguments parameter (part of the XAML2009 spec) - so the Observable Collection in your argument would be declared like:
<ObservableCollection x:TypeArguments="UserParameter">
<l:UserParameter DisplayName="Test 0" Property="Size" Type="String" />
<l:UserParameter DisplayName="Test 1" Property="Value" Type="Decimal" />
</ObservableCollection />
In general, collection properties should be plain old (non-dependency) read-only properties. The XAML parser is smart enough to add items to collection properties. For example:
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 could use it like you describe:
<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>
精彩评论