Search code examples
wpfbindingcontextmenudatacontext

Wpf ContextMenu MenuItem Header Binding


I have a ContextMenu defined in a control this way...

<Controls:MetroWindow.Resources>

    <ContextMenu x:Key="RowContextMenu">
        <MenuItem Header="{Binding CurrentLang.CmenuItemUnLockUser}"/>            
    </ContextMenu>

CurrentLang.CmenuItemUnLockUser is a string.

The DataContext is defined in the xaml (and working...):

<Controls:MetroWindow.DataContext>
    <admin:AdminViewModel/>
</Controls:MetroWindow.DataContext>

The BlockedUserContextMenu is used in a DataGrid and defined as:

<DataGrid x:Name="DgridCases"
          ItemsSource="{Binding CasesCollection"
          ...>
                <DataGrid.RowStyle>
                    <Style TargetType="{x:Type DataGridRow}">
                        <Setter Property="ContextMenu" Value="{StaticResource RowContextMenu}" />
                    </Style>
                </DataGrid.RowStyle>

CasesCollection is an ObservableCollection of CaseObject objects, i can see in the output window that can't found CurrentLang.CmenuItemUnLockUser in the CaseObject, so, the issue is related to the datacontext...

How can i specify the right datacontext?

Thanks!


Solution

  • If the CurrentLang property is defined in the AdminViewModel class, you can't bind to it directly from the DataGridRow. That's because the DataContext of the DataGridRow is the CaseObject for that particular row.

    What you could do is to bind the Tag property of the DataGridRow to the AdminViewModel using a {RelativeSource} binding:

    <DataGrid.RowStyle>
        <Style TargetType="{x:Type DataGridRow}">
            <Setter Property="Tag" Value="{Binding DataContext, RelativeSource={RelativeSource AncestorType=Window}}" />
            <Setter Property="ContextMenu" Value="{StaticResource RowContextMenu}" />
        </Style>
    </DataGrid.RowStyle>
    

    ...and then bind to the CurrentLang of the AdminViewModel using the PlacementTarget property of the ContextMenu:

    <ContextMenu x:Key="RowContextMenu">
        <MenuItem Header="{Binding PlacementTarget.Tag.CurrentLang.CmenuItemUnLockUser, 
                    RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
    </ContextMenu>