1

When you click on a control inside the ListBox (its DataTemplate), I want to know which item that is so that I can select that item.

I have a WPF application with a ListBox. Using a DataTemplate, I have a TextBlock and a Textbox inside it.

<ListBox PreviewMouseLeftButtonDown="myHandler">
  <ListBox.ItemTemplate>
    <DataTemplate>
      <StackPanel>
        <TextBlock />
        <TextBox />
      </StackPanel>
    </DataTemplate>
  </ListBox.ItemTemplate>
</ListBox>

Right now, if you click on the TextBlock, it selects the overall item. But if you click inside the TextBox (to repeat: Box, not Block), it doesn't select the item.

Is there code that I can put inside the ListBox's PreviewMouseLeftButtonDown that can tell me the index of the ListBoxItem whose TextBox I clicked? Or some other way to select the ListBoxItem?

LikeMaBell
  • 1,529
  • 2
  • 13
  • 24

2 Answers2

2

First I'd like to you to take a look again at the UI composition... textboxes as items of a listbox are rare. Listboxes are usually selectors (not editors) of items.

With that out of the way.. and if you really must have it. Use a ViewModel based approach (search for Josh Smith's MVVM article if you're new to this). The idea behind making this work would be the VM/ItemVM listen's to TextProperty's Change notification. As soon as it gets one, it finds the relevant item and toggles the item's IsSelected property. You need to bind the ListItem's IsSelected property to the VM's IsSelected property for this to work..

Gishu
  • 134,492
  • 47
  • 225
  • 308
0

if you use mvvm, use the approach Gishu gave.

if not you can use the TextBox GetFocus Event, to walk up the visual tree till the listboxitem and select it.

blindmeis
  • 22,175
  • 7
  • 55
  • 74