views:

65

answers:

2

Hi, I am adding checkboxes dynamically to silverlight stackpanel object as follows:

foreach (String userName in e.Result)
{
    CheckBox ch = new CheckBox();
    ch.Name = userName;
    ch.Content = userName;
    ContentStackPanel.Children.Add(ch);
}

How do I read back those controls to detect which of them are checked.

+3  A: 

You can use databinding to checkbox list. Something like this:

Use a Listbox to create the check list:

 <ListBox x:Name="chkList" >
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal" >
                    <CheckBox Content="{Binding userName}" IsChecked="{Binding Checked, Mode=TwoWay}"></CheckBox>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>

Then in your code just set the chklist itemSource to an ObservableCollection with your object

chkList.ItemsSource = ....
alejandrobog
I would hesitate from suggesting a ListBox here. The OP is populating a StackPanel and a ListBox is a much bigger beast with selection and mouse-over behavior that is not wanted here.Instead, an ItemsControl is a much more appropriate construct for @Manoj to use.
Brian Genisio
+1  A: 

You should probably avoid creating checkboxes in code like this. Something that might be useful for you is a mini "ViewModel" for the checkbox. Something like this:

public class Option
{
   public string Text {get; set;}
   public bool IsChecked {get; set;}
}

Then, you can have a collection of these options like this:

var options = new ObservableCollection<Option>();

Once this is populated, you can bind the ObservableCollection to an ItemsControl:

<ItemsControl ItemsSource="{Binding options}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <CheckBox Content="{Binding Text}" IsChecked="{Binding IsChecked}" />
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

That XAML will create the CheckBoxes for you for ever option you added to your options collection. The really great thing is that you can now ask you options collection which options have been selected:

var selectedNames = from option in options
                    where option.IsChecked
                    select option.Text;

Using data binding and templates is a technique you should get familiar with in Silverlight/WPF. It is a really important concept, and it will let you do amazing things in you application.

Brian Genisio