0

I have two listboxes with categories and subcategories. I would like subcategories popup when a category is clicked once.

enter image description here

Even though my code works with mouse double-click event, I couldn't work it out with one click. I tried mouse down, mouse up preview mouse down etc. They all give null reference error

    private void DataCategoryListBox_PMouseLDown(object sender, MouseButtonEventArgs e)
    {

        string selectedCat = DataCategoryListBox.SelectedItem.ToString();
        MessageBox.Show(selectedCat);

        if (selectedCat == "Geological")
        {
            string[] GeoCats = { "soil", "hydrogeology" };
            SubCatListBox.ItemsSource = GeoCats;
        }          
    }

Is there a solution to this?

Amadeus
  • 157
  • 10
  • Does this answer your question? [How to capture a mouse click on an Item in a ListBox in WPF?](https://stackoverflow.com/questions/1271375/how-to-capture-a-mouse-click-on-an-item-in-a-listbox-in-wpf) – IndieGameDev Oct 06 '20 at 13:57
  • 1
    Try the `SelectionChanged` event. – mm8 Oct 06 '20 at 14:07
  • @MathewHD that solution may work also but it is a lot easier to use SelectionChanged in my case - Thanks anyway. – Amadeus Oct 06 '20 at 14:17

1 Answers1

1

You want to know when a category is selected, therefore you should use the SelectionChanged event. When you use MouseDown, there probably isn't anything selected yet, that's why you get the null exception:

private void DataCategoryListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string selectedCat = DataCategoryListBox.SelectedItem.ToString();
    MessageBox.Show(selectedCat);

    if (selectedCat == "Geological")
    {
        string[] GeoCats = { "soil", "hydrogeology" };
        SubCatListBox.ItemsSource = GeoCats;
    }          
}
d4zed
  • 478
  • 2
  • 6
  • 16