0

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!

4
  • Could it be as simple as <ContextMenu DataContext={Binding}...? Commented May 11, 2018 at 12:03
  • Where is the CurrentLang property defined? In the AdminViewModel class or in the CaseObject class? Commented May 11, 2018 at 14:45
  • @DonBoitnott, no it doesn't works... Thanks! Commented May 11, 2018 at 18:18
  • @mm8 CurrentLang is defined in the AdminViewModel, Thanks! Commented May 11, 2018 at 18:18

1 Answer 1

2

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> 
Sign up to request clarification or add additional context in comments.

1 Comment

So smart! I usually think about tag as a string, but it's an object... Thanks!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.