简体   繁体   English

无法使用DataTemplate WPF将InputBinding应用于整个ListBoxItem

[英]Cant get InputBinding to apply to entire ListBoxItem using DataTemplate WPF

Trying to get some keybindings onto my ListBoxItems in a ListBox in WPF. 试图在WPF中的ListBox中将一些键绑定到我的ListBoxItems上。 I am using MVVM, and binding the ItemSource of the ListBox to a list of ViewModels. 我正在使用MVVM,并将ListBox的ItemSource绑定到ViewModel列表。 This ViewModel has a string and a boolean for 'Selected'. 此ViewModel具有字符串和“已选择”的布尔值。 I wish to display Selected as a property to a CheckBox. 我希望将Selected显示为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. 我试图这样做,如果我用键盘上的向上和向下箭头导航列表项,然后按Enter / space / what,我可以切换复选框。 However, I have to press tab first, to get focus to the StackPanel which contains the checkbox. 但是,我必须先按Tab键才能将焦点集中到包含复选框的StackPanel。

<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 . 我已经采取了一种方法来设置来自这个问题的样式的输入绑定。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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