Search code examples
c#wpflistboxselectionchanged

WPF ListBox selection does not work


I have a ListBox for a few items, and I need to be able to click them. Problem is, the SelectionChanged event doesn't get fired when I click on the item's text, only if I click on the blank part. I'm quite new to WPF, and I don't understand why this is happening.

XAML:

<ListBox Name="lBoxVouchers" BorderThickness="0" FontSize="15" SelectionChanged="lBoxVouchers_SelectionChanged">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <ListBoxItem Content="{Binding Name}" />
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Handler:

private void lBoxVouchers_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.AddedItems.Count > 0)
        MessageBox.Show("You just selected " + e.AddedItems[0]);
}

I'm binding the list of objects in code via the lBoxVouchers.ItemsSource property, and they show up. Each object has a Name property, of course.

I've tried setting IsEnabled on the ListBox and the items, both in code and XAML, but it doesn't help.

Any comments about better ways to do this in WPF are also welcome.


Solution

  • If you only want to show the Name property you could define your listbox like this:

    <ListBox Name="lBoxVouchers" BorderThickness="0" FontSize="15" SelectionChanged="lBoxVouchers_SelectionChanged" DisplayMemberPath="Name" />
    

    If you put your items on an ObservableCollection on code-behind, you can also pass the databinding to XAML:

    <ListBox Name="lBoxVouchers" BorderThickness="0" FontSize="15" SelectionChanged="lBoxVouchers_SelectionChanged" DisplayMemberPath="Name" ItemsSource={Binding Path=Items}" />
    

    And on your code behind you should have something like:

    ObservableCollection<object> Items {get; set}
    

    About the handler, I would also do something like this:

    private void lBoxVouchers_SelectionChanged(object sender, SelectionChangedEventArgs e) {
        if (((ListBox)sender).SelectedItem != null)
            MessageBox.Show("You just selected " + (ListBox)sender).SelectedItem);
    }