WPF ListBoxItem selection problem

后端 未结 3 1522
忘了有多久
忘了有多久 2020-12-09 10:01

I have a listbox where the items contain checkboxes:


    

        
相关标签:
3条回答
  • 2020-12-09 10:32

    You can also bind the IsChecked property of the CheckBox and IsSelected property of the ListBoxItem:

    <ListBox>
        <ListBox.ItemTemplate>
            <DataTemplate>
                <CheckBox Content="{Binding DisplayText}" IsChecked="{Binding Path=IsSelected, RelativeSource={RelativeSource AncestorType={x:Type ListBoxItem}}}"/>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
    
    0 讨论(0)
  • 2020-12-09 10:38

    To begin with, put the content outside the CheckBox:

    <StackPanel Orientation="Horizontal">
        <CheckBox IsChecked="{Binding IsChecked}"/>
        <TextBlock Text="{Binding DisplayText}"/>
    </StackPanel>
    

    After that, you will need to ensure that pressing space on a ListBoxItem results in the CheckBox being checked. There are a number of ways of doing this, including a simple event handler on the ListBoxItem. Or you could specify a handler for UIElement.KeyUp or whatever in your DataTemplate:

    <CheckBox IsChecked="{Binding IsChecked}" UIElement.KeyUp="..."/>
    
    0 讨论(0)
  • 2020-12-09 10:40

    In your use case it would be way simpler to use a ItemsControl instead of a list box. A ItemsControl is similar to a Listbox except that it doesn't contain the automatic selection behaviour. Which means that using it to host a list of what are essentially checkboxes is very simple and you don't have to workaround the ListBox's selection behaviour.

    Simply switching to ItemsControl will give you exactly what you need:

    <ItemsControl Style="{StaticResource CheckBoxListStyle}" Name="EditListBox">
        <ItemsControl .ItemTemplate>
            <DataTemplate>
                <CheckBox Click="Checkbox_Click" IsChecked="{Binding Path=IsChecked, Mode=TwoWay}" Content="{Binding Path=DisplayText}" />
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>
    

    You can click on text to check checkboxes (default behavior) and you can use the keyboard too without having to wire up any event handlers.

    0 讨论(0)
提交回复
热议问题