Search code examples
wpflistviewdatatemplatelistviewitem

ListViewItem is not selected when I clicked on the text area


I am using ListView to show a persons' names list using data template:

<Windows.Resources>
  <DataTemplate Datatype="{x:Type local:Person}">
   <ListViewItem Content="{Binding Path=Name}">
  </DataTemplates>
</Windows.Resources>
<ListView Name="myList" itemSource="{Binding}">

The code behind is

ObservableCollection<Person> lst = SomeMethod();
myList.DataContext = lst;

The listview show the persons' names, but when I click exactly on the names nothing happened (the item is not focused and SelectionChanged event doesnt work) but if Im clicking in the right part of the name in the listviewitem it works

I think is connected to the datatemple because when i removed the template and override the ToString method of person to return this.Name it works fine.

any ideas?

Thanks.


Solution

  • You shouldn't use a ListViewItem, which is a ContentControl, inside a DataTemplate, which usually describe how contents should be shown inside ContentControls, not the other way around :P

    Your DataTemplate is generating this (simplified) visual tree:

    ListView
        ItemsPresenter
            ListViewItem
                ContentPresenter
                    ListViewItem
    

    The extra ListViewItem is probably swallowing the Click event. Instead, use something like a TextBlock to show the text, and the regular ListViewItem behavior should work as intended.

    <DataTemplate Datatype="{x:Type local:Person}">
        <TextBlock Text="{Binding Path=Name}">
    </DataTemplates>