开发者

WPF 4.0 Databinding the ContextMenu on the DataGrid

开发者 https://www.devze.com 2023-02-25 11:12 出处:网络
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:

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<Conte开发者_JS百科xtMenuItem> 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>


I believe this tutorial describes your issue, but effectively you'd have to do:

<ContextMenu DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Self}}"
    ItemsSource="{Binding ContextMenuItems}" />
0

精彩评论

暂无评论...
验证码 换一张
取 消