繁体   English   中英

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

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

试图在WPF中的ListBox中将一些键绑定到我的ListBoxItems上。 我正在使用MVVM,并将ListBox的ItemSource绑定到ViewModel列表。 此ViewModel具有字符串和“已选择”的布尔值。 我希望将Selected显示为CheckBox的属性。

我试图这样做,如果我用键盘上的向上和向下箭头导航列表项,然后按Enter / space / what,我可以切换复选框。 但是,我必须先按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>

我错过了一些明显的东西???

上面的触发器在数据模板内部触发,而不是在项目容器内部触发。 因此,如果最后一个聚焦,则没有效果。

为避免这种情况,应在项目容器级别指定触发器:

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

我已经采取了一种方法来设置来自这个问题的样式的输入绑定。

暂无
暂无

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

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