简体   繁体   中英

Cant get InputBinding to apply to entire ListBoxItem using DataTemplate WPF

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???

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM