WPF How do I find which ListBox item was clicked
I have a WPF application in which there's a listbox filled with items of type 'Match'. How do I make the butt开发者_开发百科on(contained within the item) actually select the item so that I might extract the value?
Here is my code: neither works since clicking the button doesn't actually select the item
private void LayButton_Click(object sender, RoutedEventArgs e)
{
var x = (Market)ListBoxSelectedMarket.SelectedItem;
var y = (sender as ListBoxItem);
}
Thanks
You should be able to use the DataContext from the clicked Button and get the ListBoxItem container from there, and then select it.
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;
}
If you are binding to an object an alternative method could be (in VB)
This then gives you an instance of your object to play with and saves you having any mapping fields on the listbox
Private Sub OTC_Settled_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
Dim pr_YourObject As New YourObject
Dim btn As Button = CType(sender, Button)
OTC = DirectCast(btn.DataContext, pr_YourObject)
End Sub
I haven't done much WPF programming, but you could try getting the parent of the button if it works the same as a WinForms container object.
精彩评论