How to change the DataContext button of the parent parent DataContext?

I have 2 classes in WPF:

  • A meeting
  • People

During the meeting, I have 2 ObservableCollections; AttendingMeetingand NotAttendingMeetingthat contain objectsPeople

In xaml DataContextset Meeting, and I have two DataGrid( AttendingMeetingand NotAttendingMeeting)

I need to add Buttonfor each of DataGridto add and remove from Meeting. But then I need to change DataContextto Button, for example: AttendingMeetingto Meeting, so that the class Meetingcan handle adding and removing Peoplefrom ObservableCollections.

How to do this in xaml (changing elements DataContextfrom AttendingMeetingparents parent-> Meeting)?

+3
source share
1 answer

Assuming you are trying to link a command in the Meeting class from DataGrid:

You can use RelativeSourcein your binding to go to DataContextwhich is interesting to you. Your markup would look something like this:

<Grid DataContext="..."> <!-- Assuming a grid is you're layout root and that it 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 can also use ElementNameto bind to the parent object, which is of interest to you DataContext, if you are dealing with a lot of nesting, but it RelativeSourcewill be too complicated.

+3
source

Source: https://habr.com/ru/post/1718462/


All Articles