WPF:当您按下此ListItem上的按钮时,ListItem不会获得焦点

时间:2013-03-29 17:55:53

标签: c# wpf button datatemplate wpf-4.0

我有ListBox DataTemplate。模板上有Button。列表中的每个项目都显示实体。

<ListBox Grid.Column="0"
             x:Name="ThemesList"
             ItemsSource="{Binding Themes}"
             HorizontalAlignment="Left"
             VerticalAlignment="Top"
             SelectedItem="{Binding SelectedTheme}" 
             ItemTemplate="{StaticResource ThemeListTemplate}"/>

<DataTemplate x:Key="ThemeListTemplate">
    <Grid Grid.Column="1"
          Grid.Row="0"
          HorizontalAlignment="Right" 
          Margin="10">

          <Grid.RowDefinitions>
              <RowDefinition/>
              <RowDefinition/>
          </Grid.RowDefinitions>

          <Button Grid.Row="0" 
                  HorizontalAlignment="Left"
                  Style="{StaticResource ElementButton}"
                  Command="{Binding Path=DataContext.ThemeEditorViewModel.OpenThemeEditorCommand, ElementName=ThemesBacklog}"
                  CommandParameter="{Binding Path=SelectedItem, ElementName=ThemesList}">

                <TextBlock Text="Edit"/>
          </Button>

        <Button Grid.Row="1" 
                HorizontalAlignment="Left"
                Style="{StaticResource ElementButton}"
                Command="{Binding Path=DataContext.ThemeDeleteCommand, ElementName=ThemesBacklog}"
                CommandParameter="{Binding Path=SelectedItem, ElementName=ThemesList}">

                <TextBlock Text="Delete"/>
        </Button>
    </Grid>
</DataTemplate>

当您在命令中单击Button时,会传递属性值SelectedItem。当您点击ListItem然后点击Button时 - 一切正常。当我立即点击Button时 - 在命令中传递null。当您按下此ListItem上的按钮时,ListItem无法获得焦点。如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

您可以检查触发器中IsKeyboardFocusWithin上的ListBoxItems属性,以确定子项(如您的按钮)是否具有焦点,并将IsSelected设置为true是这样的。

您可以通过设置ItemContainerStyle来完成此操作:

<ListBox.ItemContainerStyle>
    <Style TargetType="{x:Type ListBoxItem}">
        <Style.Triggers>
            <Trigger Property="IsKeyboardFocusWithin" Value="True">
                <Setter Property="IsSelected" Value="True" />
            </Trigger>
        </Style.Triggers>
    </Style>
</ListBox.ItemContainerStyle>