如何获得家长';的DataContext

本文关键字:DataContext 何获得 | 更新日期: 2023-09-27 18:25:23

iv'e得到一个ListBox,它绑定到列表框的父级Player的列表作为属性为Players的数据上下文。

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

在按钮单击事件上,我需要获得与此绑定的Player的值listboxitem(包含被点击的按钮的项目)

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

如何获得家长';的DataContext

btn.DataContext应该已经包含Player,因为DataContextListBoxItem中的控件继承。

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

1) 命名列表框(比如x:name="theListBox"),并在后面的代码中检索所选玩家

var player = (Player)theListBox.SelectedValue;

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

<ListBox SelectedValue={Binding SelectedPlayer} />