Dynamically build a selection list from a list with an unknown number of members
What I am trying to do is开发者_JS百科 create a silevrlight popup that displays images to a user and lets them select a radio control underneath to determine which option they have selected. I have an object like this:
public class ConfigImage
{
public int ConfigID { get; set; }
public string ConfigName { get; set; }
public string ImagePath { get; set; }
}
The code returns a list of ConfigImage with an unknown number of members. I am trying to use a grid to display the images to the user, so I dynamically add columns based on the number of members in the list. I expect anywhere from 2-5 members to be in the list. What I am having the problem with is trying to dynamically add the image and radio controls. I cannot seem to find an example anywhere of this. I tried to add controls using code such as this:
LayoutRoot.Children.Add(new Label);
but then have no idea how to set properties on the new Label control. I should know this, but I am drawing blank and cannot seem to find an example of it.
Help would be much appreciated!
If you absolutely have to add the controls in code, you will need to have a reference to the object in order to set properties on it:
Label label = new Label();
label.Content = "text";
label.Width = 10;
LayoutRoot.Children.Add(label);
Alternatively, you can use initializers:
LayoutRoot.Children.Add(new Label()
{
Content = "text",
Width = 10
});
As BrokenGlass said, you can probably do this completely in xaml, though.
Edit: To illustrate the xaml-only approach using BrokenGlass's suggestion of ItemsControl:
<ItemsControl x:Name="ConfigImagesItemsControl" ItemsSource="MyConfigImagesList">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
<ItemsControl.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Image Grid.Row="0" Source="{Binding ImagePath}" />
<RadioButton Grid.Row="1" Content="{Binding ConfigName}" GroupName="ConfigImagesGroup" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
just use any of the list based UI elements in Silverlight - those would allow you to data bind to an observable collection that you can update at runtime, simplest one would be ItemsControl - what markup you use for each item in the collection you can completely control in XAML.
精彩评论