I have Listbox:
<ListBox x:Name="FriendsRequestList">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<StackPanel>
<TextBlock Text="{Binding FullName}" Foreground="#FF316DCB"/>
<TextBlock Text="{Binding RequestText}" />
<StackPanel Orientation="Horizontal">
<Button Name="Accept" Content="Accept" Click="Accept_Click" Foreground="#FF28901F" Background="#FFB4D8BA"/>
<Button Name="Decline" Content="Decline" Click="Decline_Click" Foreground="#FF28901F" Background="#FFB4D8BA"/>
</StackPanel>
</StackPanel>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</Listbox>
And I try these in code:
private void Accept_Click(object sender, RoutedEventArgs e)
{
Button clickedButton = sender as Button;
StackPanel st1 = clickedButton.Parent as StackPanel;
StackPanel st2 = st1.Parent as StackPanel;
StackPanel st3 = st2.Parent as StackPanel;
object parentControl = st3.Parent;
object obj = FriendsRequestList.Items[3];
int index1 = FriendsRequestList.Items.IndexOf(obj);
int index2 = FriendsRequestList.SelectedIndex;
int SenderId = FriendRequests.ElementAt(index).SenderID;
UserServices.FriendRequestAccept(this, SenderId);
UserServices.GetRequests(this);
}
index2 is -1, and parentControl is null. Why ListItem.SelectedIndex is -1?
And how can I know which ListItem button is clicked ?
The
ListBox.SelectedIndexproperty is probably -1 because theButtonis intercepting the click event and it is not being propagated to theListBox. Anyway, you don’t need the index to do what you’re trying to do.Let’s say you set the
ItemsSourceas follows:Now, assuming
FriendRequestsis some sort of collection containingFriendRequestobjects, each of which contains the propertiesFullName,RequestTextetc., modify the click handler to