Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF 4.0 Databinding the ContextMenu on the DataGrid

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.

like image 987
Exist Avatar asked Apr 14 '11 23:04

Exist


1 Answers

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>

like image 135
Exist Avatar answered Nov 02 '22 15:11

Exist