2

Trying to get some keybindings onto my ListBoxItems in a ListBox in WPF. I am using MVVM, and binding the ItemSource of the ListBox to a list of ViewModels. This ViewModel has a string and a boolean for 'Selected'. I wish to display Selected as a property to a CheckBox.

I am trying to make it so that if I navigate the list items with the up and down arrows on the keyboard, and then press enter/space/whatever, I can toggle the Checkbox. However, I have to press tab first, to get focus to the StackPanel which contains the checkbox.

<DataTemplate x:Key="MyTemplate" DataType="{x:Type ViewModel}">            
  <Border Width="2" BorderBrush="Blue">

    <i:Interaction.Triggers>
        <i:EventTrigger EventName="KeyUp">
            <i:InvokeCommandAction Command="{Binding EnterCommand}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>

    <CheckBox VerticalAlignment="Center"
              Content="{Binding Name}"
              IsChecked="{Binding Selected}"
              Margin="3" />

  </Border>
</DataTemplate>

=======================

<Popup x:Name="FilterPopup" Grid.Column="1" 
       IsOpen="{Binding IsChecked, ElementName=FilterButton}" 
       StaysOpen="False"
       PlacementTarget="{Binding ElementName=FilterButton}"
       Placement="Top">

          <ListBox ItemsSource="{Binding ViewModels}"
                   ItemTemplate="{StaticResource MyTemplate}" />

</Popup>

Have I missed something obvious???

Cameron Stubber
  • 301
  • 3
  • 14

1 Answers1

0

The triggers above are fired inside the data template, not inside item container. So if the last one is focused there is no effect.

To avoid this, the triggers should be specified on item container level:

<ListBox.ItemContainerStyle>
    <Style>
        <Setter Property="l:Attach.InputBindings">
            <Setter.Value>
                <InputBindingCollection>
                    <KeyBinding Command="{Binding EnterCommand}" Key="Enter" />
                    <KeyBinding Command="{Binding EnterCommand}" Key="Space" />
                </InputBindingCollection>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

I've taken a way to set input bindings from style from this question.

Community
  • 1
  • 1
stop-cran
  • 4,229
  • 2
  • 30
  • 47