如何获取父级的DataContext

时间:2012-02-20 16:19:17

标签: c# wpf xaml data-binding

我有一个 ListBox ,它绑定到播放器列表,列表框的父级 作为具有玩家属性的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 ?   
  }

2 个答案:

答案 0 :(得分:1)

btn.DataContext应该已包含Player,因为DataContext中的控件会继承ListBoxItem

答案 1 :(得分:1)

如果您绑定到ListBox.ItemsSource而不是ListBox.Items,那么除了H.B.的解决方案,您可以:

1)命名列表框(比如x:Name =“theListBox”)并在你的代码中检索选定的播放器

var player = (Player)theListBox.SelectedValue;

2)将SelectedPlayer属性添加到视图模型并将其绑定到列表框

<ListBox SelectedValue={Binding SelectedPlayer} />
相关问题