问题
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 DataGrid
s (AttendingMeeting
and NotAttendingMeeting
)
I need to add a Button
to each of the DataGrid
s 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 ObservableCollection
s.
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