Question

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.

Was it helpful?

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);
}

OTHER TIPS

Set IsSynchronizedWithCurrentItem="true" on the listbox.

Here you can find a starting point to get more details about this property.

Setting this property to true makes the selection be in sync with the current item which holds the actual selected item. When you click the blank space probably the current item changes to null and you get your event handler called.

may be the content in the listbox item is not stretched. just write this style for the listbox item and try.

<Style TargetType="{x:Type ListBoxItem}">
  <Setter Property="HorizontalContentAlignment" Value="Stretch" />
</Style>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top