Reputation: 775
I have this listbox :
<ListBox x:Name="MyList" ItemsSource="{Binding ListOfBullets, Mode=TwoWay, Converter=StaticResourcedebugConverter}}">
<ListBox.ItemTemplate>
<DataTemplate>
<local:TaskStepControl Text="{Binding}" AddHnadler="{Binding DelegateForHandlingAddTaskStep, ElementName=uc}"></local:TaskStepControl>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
The bindings work ok. Each local:TaskStepControl has an Add button , which is connected to AddHnadler. AddHnadler looks like this :
void AddHnadler(TaskStepControl theControl)
{
// "theControl" --> this TaskStepControl on which the Add button was pressed
//In here I want to get the index of "theControl" in the ListBox "MyList".
//I've tried
var pos = MyList.Items.IndexOf(theControl);
//pos == -1 always
}
I can not use the SelectionChanged event because the Add button on each TaskStepControl wont pass the Click event to the ListBox.
I usually work in the code behind not in xaml , so this may be very simple but I can't get it to work. I need something as simple as "IndexOf" , no MVVM stuff , as I said I usually work in the code behind not in xaml, just this time I have to implement this.
Thank you!
Upvotes: 1
Views: 964
Reputation: 84724
The ListBox works with two lists: items (from ItemsSource
) and the ListItemContainer
(the control container).
Your TaskStepControl
is a child of the ListItemContainer
and therefore available in neither list. For your purposes, I'd take advantage of the fact that DataContext
(and list item) is inherited to your TaskStepControl
:
// FYI: 'Hnadler' was a typo here
void AddHandler(TaskStepControl theControl)
{
object listItem = theControl.DataContext;
var itemContainerGenerator = MyList.ItemContainerGenerator;
DependencyObject itemContainer = itemContainerGenerator.ContainerFromItem(listItem);
int pos = itemContainerGenerator.IndexFromContainer(itemContainer);
}
Upvotes: 2