Hamma
Hamma

Reputation: 303

ListView.SelectedItems does not change when clicking a TextBox in the ItemTemplate

I have a ListView bound with an ObservableCollection. The Itemtemplate of the ListView is the following:

<ListView ItemsSource="{Binding}" IsSynchronizedWithCurrentItem="True" PreviewMouseLeftButtonUp="ListViewClicked" PreviewKeyDown="NameBox_KeyDown">
    <ListView.ItemTemplate>
        <DataTemplate>
            <StackPanel Orientation="Horizontal">
                <Image Source="./Resources/DeleteIcon.png"/>
                <TextBox Text="{Binding Path=Name}"/>
            </StackPanel>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

This way I give the user the choice to either change the name of the element, or delete it from the list. I handle this two operations in code behind through the two event handlers attached to the ListView.

The problem is that when I click on the TextBox, the SelectedItems property of the ListView doesn't change and it points the last selected item. When I click on the image or on the free space around the selection change.

Now I have two questions:

  1. Is there an easy way to fix this behavior?
  2. Is it possible to get a reference to the collection item whose property is exposed by the TextBox?

Upvotes: 1

Views: 981

Answers (1)

dkozl
dkozl

Reputation: 33384

One way to deal with this problem is to set Trigger to set IsSelected when keyboard focus is within ListViewItem

<ListView ... SelectionMode="Single">
    <!-- .... -->
    <ListView.ItemContainerStyle>
        <Style TargetType="{x:Type ListViewItem}">
            <Style.Triggers>
                <Trigger Property="IsKeyboardFocusWithin" Value="True">                        
                    <Setter Property="IsSelected" Value="True"/>
                </Trigger>
            </Style.Triggers>
        </Style>
    </ListView.ItemContainerStyle>
</ListView>

Upvotes: 2

Related Questions