I'm having a hell of a time trying to dynamically bind the ContextMenu on a DataGrid. The DataGrid is bound to a list of objects which works great:
<DataGrid ItemsSource="{Binding DataGridItems}">
For each of the DataGridItem objects I have a list of MenuItems exposed on a property which I would like to use to bind to the ContextMenu. I tried the below but I think I’m missing something:
<DataGrid ItemsSource="{Binding DataGridItems}">
<DataGrid.ContextMenu>
<ContextMenu ItemsSource="{Binding ContextMenuItems}" >
<MenuItem Header="{Binding Name}" Command="{Binding OnClick}"></MenuItem>
</ContextMenu>
</DataGrid.ContextMenu>
<DataGrid>
public class DataGridItem
{
public ObservableCollection<ContextMenuItem> ContextMenuItems
{
get { return _contextMenuItems; }
}
}
Any help or guidance would be much appreciated.
This is how I ended up solving it:
<StackPanel.ContextMenu>
<ContextMenu ItemsSource="{Binding ContextMenu}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding OnClick}" />
<Setter Property="Icon">
<Setter.Value>
<Image Source="{Binding ImageName}"></Image>
</Setter.Value>
</Setter>
</Style>
</ContextMenu.ItemContainerStyle>
<ContextMenu.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type ContextMenu:ContextMenuItem}" ItemsSource="{Binding MenuItems}">
<TextBlock Text="{Binding Name}"></TextBlock>
</HierarchicalDataTemplate>
</ContextMenu.ItemTemplate>
</ContextMenu>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With