Listbox.ItemContainerStyle选中的项目

时间:2016-10-18 06:52:28

标签: c# wpf listbox

我有一个带有ItemContainerStyle的列表框,它描述了列表框中每个元素的样式。像看起来像这样:

<ListBox.ItemContainerStyle>
    <Style TargetType="ListBoxItem" BasedOn="{StaticResource MyStyle}">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Border BorderThickness="0,0,0,1" BorderBrush="#1f000000"  Padding="16 8">
                        <Button Command={Binding MyCommand, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=lists:MyControl}}}" />
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</ListBox.ItemContainerStyle>

问题是,当我单击此按钮时,我想知道列表框中的SelectedItem,它在我的ViewModel中绑定。除非我先选择项目,否则此选择不会触发。

任何想法?

1 个答案:

答案 0 :(得分:3)

您需要使用触发器强制IsSelected:

 <Style.Triggers>
       <Trigger Property="IsKeyboardFocusWithin" Value="True">
                 <Setter Property="IsSelected" Value="True"/>
       </Trigger>
 </Style.Triggers>

以下是一个完整的工作示例:

 <ListBox x:Name="ListBox" ItemsSource="{Binding SomeList}" SelectedItem="{Binding SelectedListElement, Mode=TwoWay}" IsSynchronizedWithCurrentItem="True" >
    <ListBox.ItemContainerStyle>
            <Style TargetType="ListBoxItem" >
                <Style.Triggers>
                    <Trigger Property="IsKeyboardFocusWithin" Value="True">
                        <Setter Property="IsSelected" Value="True"/>
                    </Trigger>
                </Style.Triggers>
                <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate>
                        <Border BorderThickness="0,0,0,1" BorderBrush="#1f000000"  Padding="16 8">
                                <Button Command="{Binding RelativeSource={RelativeSource AncestorType={x:Type ListBox}},
                                Path=DataContext.Run}" CommandParameter="{Binding}"  Height="30" Width="100"/>
                        </Border>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.ItemContainerStyle>
 </ListBox>