Search code examples
wpflistviewselecttextboxfocus

How to select a ListView item if I focus the TextBox inside that item?


I have a ListView like below. Colum 2 is TextBox that I can rename item.
When I focus to TextBox, I want the listview's row that contain that TextBox is selected, too. How can I do that? Thank!

<ListView x:Name="lb" ItemsSource="{Binding}">
    <ListView.View>
        <GridView>
            <GridViewColumn Width="25">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=Next}"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
            <GridViewColumn Width="Auto">
                <GridViewColumn.CellTemplate>
                    <DataTemplate>
                        <TextBox Text="{Binding Path=Path}"/>
                    </DataTemplate>
                </GridViewColumn.CellTemplate>
            </GridViewColumn>
        </GridView>
    </ListView.View>
</ListView>

Solution

  • Use Style

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