I'm trying to make Context Menu, which will have items depending on some data in code. So, i have simple class, determining single item of menu
class ContextMenuItem
{
public string ItemHeader {get; set;}
public Command ItemAction {get; set;
}
where Command is implementation of ICommand, and stores action, which will be fired once this item is selected. Then i have class, serving as DataContext
class SomeClass
{
public List<ContextMenuItem> ContextMenuItems {get; set;}
public string SomeProperty {get; set;}
public string SomeAnotherProperty {get; set;}
}
So, ContextMenuItems is list of actions I need in my context menu, which can be generated using different approaches.
And I'm creating dynamic context menu, using this approach.
<ContextMenu ItemsSource="{Binding ContextMenuItems}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Command" Value="{Binding ItemAction}"/>
<Setter Property="Header" Value="{Binding ItemHeader}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
So, i was suspecting this to work well. But, for some reason, binding works not the way I want it to.
<Setter Property="Command" Value="{Binding ItemAction}"/>
<Setter Property="Header" Value="{Binding ItemHeader}"/>
Somehow, data context for this lines is not ContextMenuItem
, but SomeClass
itself. So, i can bind SomeProperty and SomeAnotherProperty here, but not ItemHeader or ItemAction. And this ruins whole idea of dynamicaly created context menu.
So, how can i make this template recognize ContextMenuItem as its DataContext?
What i want to do can be accomplished using DataTemplate, but it gives us MenuItem inside MenuItem, and this is not good.
Update
Full xaml code involving ListBox
<ListBox Margin="5, 5" Background="White" ItemsSource="{Binding SwitchAgents, UpdateSourceTrigger=PropertyChanged}" HorizontalContentAlignment="Stretch">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid Margin="3,1">
<Grid.ContextMenu>
<ContextMenu ItemsSource="{Binding ContextMenuItems}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="MenuItem">
<Setter Property="Command" Value="{Binding ItemAction}"/>
<Setter Property="Header" Value="{Binding ItemHeader}"/>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</Grid.ContextMenu>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="7*"/>
</Grid.ColumnDefinitions>
<CheckBox IsChecked="{Binding Enabled, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,3"/>
<TextBlock Text="{Binding ObjectName}" Grid.Column="1" Margin="0,2"/>
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>