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

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-01 06:56:25

问题


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:


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.



来源:https://stackoverflow.com/questions/1471643/how-to-change-the-datacontext-of-a-button-to-the-parents-parent-datacontext

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!