【问题标题】:How to get parent's DataContext如何获取父母的 DataContext
【发布时间】:2012-02-20 16:19:16
【问题描述】:

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

【问题讨论】:

    标签: c# wpf xaml data-binding


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      var player = (Player)theListBox.SelectedValue;
      

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

      <ListBox SelectedValue={Binding SelectedPlayer} />
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-04-04
        • 1970-01-01
        • 2017-01-23
        • 2010-12-01
        • 2013-05-05
        • 2010-12-16
        • 1970-01-01
        • 2015-08-30
        相关资源
        最近更新 更多