WPF, ListBox's ItemTemplate has CheckBox, but CheckBox does not seem to be the item
Asked Answered
S

2

7

I just wanted the CheckListBox I used to use with Windows Forms.

    <ListBox>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox  Content="{Binding Name}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>

At first this seemed to work, but there was numerous problems. In short, it just works like a CheckBox is floating on the real item, rather than the CheckBox is the item.

I mean, (1)clicking the checkbox's text would not select the ListBox item, (2)pressing up and down key does not focus the checkbox. I have to click the checkbox in order to focus it. I have searched Google for solutions but there weren't clean solutions. Am I wanting too much?

I just want the behavour of CheckedListBox...

I worked around (1) by handling the PreviewMouseDown event of the checkbox and manually selecting the item. It does not seem to be clean.

Some answered 5/5, 2011 at 17:16 Comment(0)
W
9

This is, because your CheckBox is in a ListBox. It is handled as an item of the list with all it's features.

If you want to build only a list of checkboxes and don't need selection-logic of the list, use an ItemsControl instead of the ListBox. The usage is equal. If you want to have your CheckboxList scrollable, use ScrollViewer to wrap the ItemsControl.

<ScrollViewer>
   <ItemsControl ItemsSource="{Binding YourItemsCollection">
      <ItemsControl.ItemTemplate>    
          <DataTemplate>                
             <CheckBox  Content="{Binding Name}"/>
          </DataTemplate>
      </ItemsControl.ItemTemplate>
   </ItemsControls>
</ScrollViewer>
Whistle answered 5/5, 2011 at 17:18 Comment(0)
D
0

Selected answer for the linked question (WPF ListBoxItem selection problem) provides a clean solution! Was stuck with the same scenario -> found your question -> found the other one with the remedy. HTH!

Dumdum answered 12/12, 2012 at 16:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.