Retrieving Selected Items from Checked List Box?

306 views Asked by At

I've implemented a Checked List Box (or rather, tried to implement a checked list box), and it's gone pretty well. I've been able to populate it with a list of files from a directory (which is what for I need it), but when I select the items, and then try and check the .SelectedItems property, there's nothing in the list.

This is the XAML:

<ListBox x:Name="lbxSourceFiles" x:FieldModifier="private" SelectionMode="Multiple" Grid.Column="1" Grid.Row="2">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ListBoxItem IsSelected="{Binding IsChecked}">
                <CheckBox Content="{Binding Name}" Tag="{Binding FullName
            </ListBoxItem>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

This is how I populate it :

DirectoryInfo DI = new DirectoryInfo("Trivia Source Files");
this.lbxSourceFiles.ItemsSource = new ObservableCollection<FileInfo>( DI.GetFiles( "*.xls" ) );

Clearly I am doing something wrong here, and I've seen posts everywhere about how to create these things, but I can't figure out how to make it work for actually selecting items.

Please tell me what I am doing wrong here.

1

There are 1 answers

0
Posix On BEST ANSWER

Your DataTemplate is wrong. You create another ListBoxItem, so simplified visual tree looks something like this:

+- ListBox
|  +- ListBoxItem
|  |  +- ListBoxItem
|  |     +- CheckBox
|  +- ListBoxItem
|  |  +- ListBoxItem
|  |     +- CheckBox
|  +- ListBoxItem
|  |  +- ListBoxItem
|  |     +- CheckBox

Just remove ListBoxItem from DataTemplate and set Binding in CheckBox, where you find correct ListBoxItem

<DataTemplate>
    <CheckBox Content="{Binding Name}"
        IsChecked="{Binding 
            RelativeSource={RelativeSource 
                Mode=FindAncestor, 
                AncestorType={x:Type ListBoxItem}},
            Path=IsSelected,
            Mode=TwoWay}"
    Tag="{Binding FullName}" />
</DataTemplate>