WPF如何查找单击了哪个ListBox项

Chr*_*ris 7 wpf listbox click button listboxitem

我有一个WPF应用程序,其中有一个列表框中填充了"匹配"类型的项目.如何使按钮(包含在项目中)实际选择项目以便我可以提取值?

这是我的代码:既不起作用,因为单击按钮实际上并不选择该项目

private void LayButton_Click(object sender, RoutedEventArgs e)
{
    var x = (Market)ListBoxSelectedMarket.SelectedItem;
    var y = (sender as ListBoxItem);

}
Run Code Online (Sandbox Code Playgroud)

谢谢

Fre*_*lad 12

您应该能够使用单击的Button中的DataContext并从那里获取ListBoxItem容器,然后选择它.

private void LayButton_Click(object sender, RoutedEventArgs e)
{  
    Button button = sender as Button;
    var dataContext = button.DataContext;
    ListBoxItem clickedListBoxItem = ListBoxSelectedMarket.ItemContainerGenerator.ContainerFromItem(dataContext) as ListBoxItem;
    clickedListBoxItem.IsSelected = true;
}
Run Code Online (Sandbox Code Playgroud)