0

私はリストボックスを持っています:

  <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 ボタンがクリックされたかをどのように知ることができますか?

4

1 に答える 1

13

がクリック イベントをインターセプトし、 に伝達されていないため、ListBox.SelectedIndexプロパティはおそらく -1 です。とにかく、やろうとしていることをするためにインデックスは必要ありません。ButtonListBox

を次のように設定したItemsSourceとします。

FriendsRequestList.ItemsSource = FriendRequests;

ここで、オブジェクトFriendRequestsを含むある種のコレクションがあり、それぞれがプロパティなどを含むと仮定して、クリック ハンドラーを次のように変更します。FriendRequestFullNameRequestText

private void Accept_Click(object sender, RoutedEventArgs e)
{
  FriendRequest req = ( sender as Button ).DataContext as FriendRequest;
  int senderID = req.SenderID;
  ...
}
于 2011-10-11T15:22:39.237 に答える