如何改变一个按钮,父母家长的DataContext的DataContext的? [英] How to change the DataContext of a button to the parents parent DataContext?
问题描述
我有2班在WPF:
- 会议
- 个人
在会议上,我已经2 ObservableCollections
; AttendingMeeting
和 NotAttendingMeeting
包含人
对象
In meeting I have 2 ObservableCollections
; AttendingMeeting
and NotAttendingMeeting
that contain People
objects
在XAML的的DataContext
设置为会议
,我有2 的DataGrid
S( AttendingMeeting
和 NotAttendingMeeting
)
In the xaml the DataContext
are set to Meeting
, and I have 2 DataGrid
s (AttendingMeeting
and NotAttendingMeeting
)
我需要一个按钮
添加到每个的DataGrid
取值添加和<$ C $删除C>会议,但后来我需要将的DataContext
在按钮
,例如从改变: AttendingMeeting
到会议
,使会议
类可以处理添加和删除人
从的ObservableCollection
秒。
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.
我怎样才能做到这一点在XAML(修改的DataContext
从 AttendingMeeting
项目向父母父 - &GT;会议
)
How can I do this in xaml (changing the DataContext
from AttendingMeeting
items to the parents parent-> Meeting
)?
推荐答案
假设你试图绑定到一个命令在会议类从的DataGrid
中:
Assuming you're trying to bind to a Command on the Meeting class from within the DataGrid
:
您可以在您的结合才能到的DataContext
你有兴趣使用的RelativeSource
。你'重新标记将类似于这样:
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>
您也可以使用的ElementName
绑定到具有的DataContext
你感兴趣,如果你的父母再处理大量嵌套和的RelativeSource
太复杂了。
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.
这篇关于如何改变一个按钮,父母家长的DataContext的DataContext的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!