0

I have a ListBox with a DataTemplate. The template has a Button on it. Each item in the list shows the entity.

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

When you click on Button in the command is passed the property value SelectedItem. When you click on ListItem and then click Button - all fine. When I at once click on the Button - in the command is passed null. That is ListItem does not receive focus when you press the button located on this ListItem. How to solve this problem?

Anatoliy Nikolaev
  • 22,370
  • 15
  • 69
  • 68
sribin
  • 1,736
  • 1
  • 13
  • 21

1 Answers1

0

You could examine the IsKeyboardFocusWithin property on the ListBoxItems in a trigger, to find out whether a child (like your button), has focus, and set IsSelected to true if that is the case.

You do this by setting the ItemContainerStyle like this:

<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>
Peter Hansen
  • 8,807
  • 1
  • 36
  • 44