我想获得column Index
并通过CommandParameter
context menu
传递给Data grid column header
。
<DataGrid.Resources>
<ContextMenu x:Key="DataGridColumnHeaderContextMenu">
<MenuItem Header="Freez Column"
Command="{Binding DataContext.FreezColumnCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}" />
</ContextMenu>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="ContextMenu" Value="{StaticResource DataGridColumnHeaderContextMenu}" />
</Style>
</DataGrid.Resources>
我试图通过在Binding
中传递CommandParameter
来传递整个对象,但它只会传递标题文字。
尝试使用RelateveSource AncestorType=DataGridColumn
仍然无法理解。
修改
DataGrid代码:
<DataGrid ItemsSource="{Binding MyList}" HorizontalScrollBarVisibility="Visible" CanUserAddRows="False" AutoGenerateColumns="False">
<DataGrid.Resources>
<ContextMenu x:Key="DataGridColumnHeaderContextMenu">
<MenuItem Header="Freez Column"
Command="{Binding DataContext.FreezColumnCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding}" />
</ContextMenu>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="ContextMenu" Value="{StaticResource DataGridColumnHeaderContextMenu}" />
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="Story" Binding="{Binding Story}" />
<DataGridCheckBoxColumn Header="Design" Binding="{Binding Design}" />
<DataGridTextColumn Header="CadId" Binding="{Binding CadId}" />
</DataGrid.Columns>
</DataGrid>
答案 0 :(得分:4)
发生这种情况可能是因为ContextMenu
被单独维护VisualTree
(如果我错了,请纠正我)。请使用以下代码获取DisplayIndex
,
<DataGrid
x:Name="myGrid"
AutoGenerateColumns="False"
CanUserAddRows="False"
HorizontalScrollBarVisibility="Visible"
ItemsSource="{Binding Persons}">
<DataGrid.Resources>
<local:GridToIndexConverter x:Key="GridToIndexConverter" />
<ContextMenu x:Key="DataGridColumnHeaderContextMenu">
<MenuItem
Command="{Binding DataContext.FreezColumnCommand, RelativeSource={RelativeSource AncestorType=DataGrid}}"
CommandParameter="{Binding PlacementTarget.DisplayIndex, RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ContextMenu}}"
Header="Freez Column" />
</ContextMenu>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="ContextMenu" Value="{StaticResource DataGridColumnHeaderContextMenu}" />
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Binding="{Binding Story}" Header="Story" />
<DataGridCheckBoxColumn Binding="{Binding Design}" Header="Design" />
<DataGridTextColumn Binding="{Binding CadId}" Header="CadId" />
</DataGrid.Columns>
</DataGrid>
我访问了PlacementTarget
的{{1}}。