WPF如何将DataGridCell内DataTemplate绑定到列Header
解决DataGrid按钮CommandParameter绑定列Header为null的问题
你的问题根源在于DataGrid的列对象(如DataGridBoundTemplateColumn)不在可视化树中,所以通过RelativeSource={RelativeSource AncestorType=control:DataGridBoundTemplateColumn}无法找到目标对象,导致绑定返回null。
可行解决方案
直接绑定到按钮所在的DataGridCell的Column.Header属性——DataGridCell属于可视化树的一部分,能被RelativeSource正确定位,且它的Column属性直接关联对应的列对象:
修改ButtonTemplate中的CommandParameter绑定:
<Button Content="{Binding Name}" CommandParameter="{Binding Column.Header, RelativeSource={RelativeSource AncestorType=DataGridCell}}" Command="{Binding DataContext.NewCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"> </Button>
原理说明
DataGridCell是按钮的直接可视化父容器之一,通过RelativeSource AncestorType=DataGridCell可以准确找到它。DataGridCell.Column属性指向当前单元格所属的DataGridBoundTemplateColumn,因此Column.Header就能拿到你需要的列标题值。
验证效果
修改后,点击不同列的按钮时,NewCommandExecute中的commandParameter会正确传入对应列的Header文本(如"Powerbar"、"Circuit Breaker"),你的switch逻辑可以正常工作。
内容的提问来源于stack exchange,提问作者Antoine Carpentier
相关产品推荐
相关产品推荐

