2012-02-20 73 views
0

iv'e有一個列表框這勢必球員,列表框的父 與玩家的屬性的datacontext的列表。如何獲得家長的DataContext的

<ListBox> 
     <ListBox.Items> 
      <Binding Path="Players"></Binding> 
     </ListBox.Items> 
     <DataTemplate> 
      <ListBoxItem>           
       <TextBlock Text="{Binding Name}"></TextBlock> 
       <Button ToolTip="Invite To Play" x:Name="btn_InviteToPlay" Click="btn_InviteToPlay_Click>           
      </ListBoxItem> 
     </DataTemplate> 
     </ListBox.ItemTemplate> 
    <ListBox> 

上的按鈕單擊事件中,我需要得到球員綁定到這個 ListBoxItem的價值

private void btn_InviteToPlay_Click(object sender, RoutedEventArgs e) 
    { 
     Button btn = (Button)sender; 
     // how to retrieve player bound to current listboxitem ? 
    } 

回答

1

btn.DataContext應該已經包含(包含所單擊按鈕的那一個)作爲DataContextPlayerListBoxItem中的控件繼承。

1

如果你除了再結合ListBox.ItemsSource而不是ListBox.Items到HB的解決方案你可以:

1)名稱列表框(例如x:名稱=「theListBox」)和檢索在代碼中選擇播放器背後

var player = (Player)theListBox.SelectedValue; 

2)SelectedPlayer屬性添加到您的視圖模型並結合,爲您的列表框

<ListBox SelectedValue={Binding SelectedPlayer} />