我在WPF中有两个类:
在开会中我有2 ObservableCollections
;包含AttendingMeeting
个对象的NotAttendingMeeting
和People
在xaml中,DataContext
设置为Meeting
,我有2 DataGrid
s(AttendingMeeting
和NotAttendingMeeting
)
我需要为每个Button
添加DataGrid
来添加和删除Meeting
,但我需要更改DataContext
Button
1}}从例如:AttendingMeeting
到Meeting
,以便Meeting
类可以处理从People
添加和删除ObservableCollection
。
如何在xaml中执行此操作(将DataContext
从AttendingMeeting
项更改为父项parent-> Meeting
)?
答案 0 :(得分:3)
假设您正尝试从DataGrid
中绑定到Meeting类上的Command:
您可以在绑定上使用RelativeSource
来访问您感兴趣的DataContext
。您的标记看起来与此类似:
<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>
如果您处理大量嵌套而ElementName
过于复杂,您还可以使用DataContext
绑定到您感兴趣的RelativeSource
的父级。