[英]WPF/C#: How to make a selection from a listbox with one click?
I have two listboxes with categories and subcategories.我有两个带有类别和子类别的列表框。 I would like subcategories popup when a category is clicked once.
我想在单击一次类别时弹出子类别。
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?这个问题有方法解决吗?
You want to know when a category is selected, therefore you should use the SelectionChanged event.您想知道何时选择了类别,因此您应该使用 SelectionChanged 事件。 When you use MouseDown, there probably isn't anything selected yet, that's why you get the null exception:
当您使用 MouseDown 时,可能还没有选择任何内容,这就是您收到 null 异常的原因:
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.