如何在Listbox中知道单击了哪个ListItem按钮?

时间:2011-10-11 15:13:14

标签: silverlight windows-phone-7 listbox controltemplate selectedindex

我有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>

我在代码中尝试这些:

  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为-1,parentControl为null。为什么ListItem.SelectedIndex是-1? 我怎么知道单击了哪个ListItem按钮?

1 个答案:

答案 0 :(得分:13)

ListBox.SelectedIndex属性可能为-1,因为Button正在拦截click事件,并且它未传播到ListBox。无论如何,你不需要索引去做你想要做的事情。

假设您将ItemsSource设置如下:

FriendsRequestList.ItemsSource = FriendRequests;

现在,假设FriendRequests是某种包含FriendRequest个对象的集合,每个对象都包含属性FullNameRequestText等,请将点击处理程序修改为< / p>

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