How to change the DataContext of a button to the p

2019-02-18 18:41发布

I have 2 Classes in WPF:

  • Meeting
  • People

In meeting I have 2 ObservableCollections; AttendingMeeting and NotAttendingMeeting that contain People objects

In the xaml the DataContext are set to Meeting, and I have 2 DataGrids (AttendingMeeting and NotAttendingMeeting)

I need to add a Button to each of the DataGrids to add and remove from Meeting, But then I need to change the DataContext on the Button from e.g.: AttendingMeeting to Meeting, so that the Meeting class can handle the adding and removing People from the ObservableCollections.

How can I do this in xaml (changing the DataContext from AttendingMeeting items to the parents parent-> Meeting)?

1条回答
爷、活的狠高调
2楼-- · 2019-02-18 19:39

Assuming you're trying to bind to a Command on the Meeting class from within the DataGrid:

You can use a RelativeSource on your binding to get to the DataContext you're interested in. You're markup would look something similar to this:

<Grid DataContext="..."> <!-- Assuming a grid is you're layout root and that it's datacontext is the Meeting you spoke of -->
   ...
   <DataGrid ...>
      ...

      <Button Content="Click Me!"
              Command="{Binding Path="DataContext.RemovePersonCommand"
                                RelativeSource={RelativeSource FindAncestor,
                                                AncestorType={x:Type Grid}}}"
              CommandParameter="{Binding}"/> <!-- This would be binding to the current person -->
      ...
   </DataGrid>
   ...
</Grid>

You could also use ElementName to bind to a parent that has the DataContext you're interested in if you're dealing with lots of nesting and a RelativeSource would be too complicated.

查看更多
登录 后发表回答