WPF/C#: How to make a selection from a listbox with one click?

269 views Asked by At

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?

1

There are 1 answers

1
d4zed On BEST ANSWER

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