开发者

How to know in Listbox which ListItem button is clicked?

开发者 https://www.devze.com 2023-04-12 01:27 出处:网络
I have Listbox: <ListBox x:Name=\"FriendsRequestList\"> <ListBox.ItemTemplate> <DataTemplate>

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.SelectedIndex property is probably -1 because the Button is intercepting the click event and it is not being propagated to the ListBox. Anyway, you don't need the index to do what you're trying to do.

Let's say you set the ItemsSource as follows:

FriendsRequestList.ItemsSource = FriendRequests;

Now, assuming FriendRequests is some sort of collection containing FriendRequest objects, each of which contains the properties FullName, RequestText etc., modify the click handler to

private void Accept_Click(object sender, RoutedEventArgs e)
{
  FriendRequest req = ( sender as Button ).DataContext as FriendRequest;
  int senderID = req.SenderID;
  ...
}
0

精彩评论

暂无评论...
验证码 换一张
取 消