开发者

Click on ListBox with DataTemplate, select ListBox Item [duplicate]

This question already has an answer here: ListBoxItem selection on TextBox focus (1 answer) Closed 3 years ago.

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?


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜