在WPF中使用DataGrid,有时会用到ContextMenu,当ContextMenu需要绑定DataGrid列的时候,我们按平时的绑定就直接用ElementName的方式了,但在ContextMenu中是不可
以的,可以用以下方式进行绑定:
<MenuItem ItemsSource="{Binding PlacementTarget.Columns, RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type ContextMenu}, Mode=FindAncestor}}">
在使用MenuItem时,有时会用到模板列,如下:
<MenuItem.ItemTemplate> <DataTemplate> <CheckBox x:Name="CurrentCheck" Content="{Binding Header,UpdateSourceTrigger=PropertyChanged}" IsChecked="{Binding Visibility}"/> </DataTemplate> </MenuItem.ItemTemplate>
但当我在后台获取MenuItem的Items的每一个CheckBox时发现获取不到了。。。怎么办呢,最后尝试着用ItemContainerStyle解决了问题,看下边:
Xaml:
<MenuItem.ItemContainerStyle> <Style TargetType="MenuItem"> <Style.Setters> <Setter Property="Template"> <Setter.Value> <ControlTemplate> <MenuItem> <MenuItem.Header> <CheckBox x:Name="CurrentCheck" Content="{Binding Header,UpdateSourceTrigger=PropertyChanged}" IsChecked="{Binding Visibility}"/> </MenuItem.Header> </MenuItem> </ControlTemplate> </Setter.Value> </Setter> </Style.Setters> </Style> </MenuItem.ItemContainerStyle>
foreach (var item in VisColumn.Items) { MenuItem itdem = VisColumn.ItemContainerGenerator.ContainerFromItem(item) as MenuItem; CheckBox check = itdem.Template.FindName("CurrentCheck", itdem) as CheckBox; //...... }