我有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按钮?
答案 0 :(得分:13)
ListBox.SelectedIndex
属性可能为-1,因为Button
正在拦截click事件,并且它未传播到ListBox
。无论如何,你不需要索引去做你想要做的事情。
假设您将ItemsSource
设置如下:
FriendsRequestList.ItemsSource = FriendRequests;
现在,假设FriendRequests
是某种包含FriendRequest
个对象的集合,每个对象都包含属性FullName
,RequestText
等,请将点击处理程序修改为< / p>
private void Accept_Click(object sender, RoutedEventArgs e)
{
FriendRequest req = ( sender as Button ).DataContext as FriendRequest;
int senderID = req.SenderID;
...
}