<Grid Name="hehe"> <Border Name="bibi"> <DataGrid Name="haha" Width="200"> <DataGrid.ContextMenu> <ContextMenu> <MenuItem Header="{Binding Path=Name, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Grid}}"/> <MenuItem Header="{Binding Path=Name, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Border}}"/> <MenuItem Header="{Binding Path=Name, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=DataGrid}}"/> </ContextMenu> </DataGrid.ContextMenu> </DataGrid> </Border> <TextBox Width="100" HorizontalAlignment="Left" Text="{Binding Path=Name, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Grid}}"/> </Grid>
运行结果
3个DataGrid右键菜单项的绑定,一个TextBox的绑定,都是绑定到上级控件的name属性上。
上面4各数据绑定,右键菜单上(MenuItem)的3个都绑定失败了,没有数据。最后TextBox的绑定成功了,
绑定语句看了很久没发现不对,有人知道问题出在哪里吗?
绑定语句都是一样的
ContextMenu 是Grid的属性,不是子元素,FindAncestor是找不着的吧?你直接绑定name或者x:name吧
ContextMenu 不在 VistualTree 里面,你可以找找相关内容