tags:

views:

203

answers:

1

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

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.

dustyburwell
Thanks for guiding me into a solution.This is my working Command Binding:Command="{Binding ElementName=SelectedMeeting, Path=DataContext.AddPatientsToMeetingCommand}" CommandParameter="{Binding}"
code-zoop
Personally I'd prefer using ElementName instead of climbing the tree looking for ancestor. This gives a direct reference to the element you want to use instead of relying on the structure not to change in a way that affects your tree climbing (adding another grid at some point between).
stiank81
Glad to have helped. @bambuska, I agree...tree climbing is definitely not the best approach, especially when looking for something as common as a Grid.
dustyburwell