views:

214

answers:

1

I have a listbox, which is defined like so:

<ListBox ItemsSource="{Binding Source={x:Static local:ResourceCollection.resourceList}}" Height="143" HorizontalAlignment="Left" Margin="6,6,0,0" Name="assignmentLB" VerticalAlignment="Top" Width="287" FontSize="12" FontWeight="Normal" IsEnabled="True" Grid.Column="0">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <CheckBox />
                <TextBlock Text="{Binding Content}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

How can I loop through this listbox and retrieve the TextBlock.Text value for only items whose Checkbox has been checked?

Also... how can I horizontally space out the checkbox from the textblock. Right now they are right next to each other with no spacing.

+2  A: 

Add a boolean property to the class you are binding to (the same one with the Content property) and bind the CheckBox to it, like this:

<CheckBox IsChecked="{Binding IsSelected}"/>

Then you can simply loop through the resourceList and grab all the items that have IsSelected set to true, like this:

resourceList.Where(r => r.IsSelected);

As for the horizontal spacing, you just need to supply a Margin to either the CheckBox or the TextBlock, or both. A margin of 5,0 on the TextBlock should be all you need.

Charlie
Nice! I bet I'll need to use this approach someday.
Dave
My static class (ResourceCollection) is shared amongst several windows. For example: there can be several windows open, all sharing the same ResourceCollection. If I modify that then it would cause issues in other windows.
Chris Klepeis
Well unless the other windows also reference this new selected property, you won't see any changes in them. This is the RIGHT way to do it, and if this isn't possible then you need to make some infrastructure changes. Worst case scenario, you wrap your resource class in a data-binding class that contains the selected property, then bind to that class in your ListBox for this particular window.
Charlie
@Charlie - Good idea. I'll wrap it in another class. Thanks.
Chris Klepeis