Reputation: 33
One of those 'Why is this so hard?" questions.
I have a ListBox
(containing details of share portfolios). The listbox item uses a grid to display attributes of the portfolio. Source is a list of portfolios in the View Model.
ListBox
is multiselect - when selection changes, a list of the constituents of the selected portfolios is re-populated.
What I want to do is put a button (or menu or whatever) on the listboxitem to display a list of possible actions (Trade, Unitise, Delete etc).
When an action is selected I need to execute the action against the appropriate portfolio. Ideally I want the actions to be available for both selected and unselected items.
I can handle the event, but how do I detect which item (portfolio) the user selected? I've looked at GotFocus() but it doesn't seem to fire.
In other words if a control in a Listboxitem, fires an event, how does the event 'know' which ListBoxItem
raised it?
Upvotes: 0
Views: 56
Reputation: 169150
I can handle the event, but how do I detect which item (portfolio) the user selected? I've looked at
GotFocus()
but it doesn't seem to fire.
You could cast the DataContext
of the clicked Button
to the corresponding object in te ListBox
, e.g.:
private void DeleteButton_Clicked(object sender, RoutedEventArgs e)
{
Button deleteButton = sender as Button;
var portfolio = deleteButton.DataContext as Portfolio; //or whatever your type is called
//access any members of the portfolio...
}
Upvotes: 0
Reputation: 5208
For me, the solution here, seen as you mentioned MVVM, would be to have the ListBox
populated by a collection of ViewModels, e.g., something like ObservableCollection<PortfolioViewModel>
.
It would then just be a case of binding the Command
property of the Button
to an ICommand
on the ViewModel that executes whatever work you need doing.
Upvotes: 1