I have a context menu on a button, which I have added in xaml as follows:
<Button Content="{Binding MaterialLabel}"
Command="{Binding SwapCommand}">
<Button.Resources>
<ContextMenu x:Key="RClickSwaps" ItemsSource="{Binding SwapList}">
<ContextMenu.ItemContainerStyle>
<Style TargetType="{x:Type MenuItem}">
<Setter Property="Header" Value="{Binding targetMaterial.Component_Code}"/>
<Setter Property="Command" Value="{Binding RClickSwapCommand}"/>
<Setter Property="ToolTip">
<Setter.Value>
<ContentControl>
<Border CornerRadius="2" BorderThickness="2">
<TextBlock Text="{Binding targetMaterial.Component_Name}"/>
</Border>
</ContentControl>
</Setter.Value>
</Setter>
</Style>
</ContextMenu.ItemContainerStyle>
</ContextMenu>
</Button.Resources>
</Button>
The Binding for the UserControl
as a whole is to a view model which contains a collection (SwapList
) of classes that contain the command and TargetMaterial
properties for the context menu used above:
//Control View Model
public ObservableCollection<SwapMenuItem> SwapList { get; set; }
//... Some irrelevant Code excluded ...
SwapList = new ObservableCollection<SwapMenuItem>();
var swaps = new ObservableCollection<Raw_Materials>(await ComponentDataService.GET_MaterialSwaps(New_Material));
foreach (var item in swaps)
{
SwapList.Add(new SwapMenuItem(item, this));
}
OnPropertyChanged("SwapList");
The SwapMenuItem
itself contains the following properties and a command that look a bit like this:
public class SwapMenuItem : Observable
{
public ComponentChangeViewModel ComponentChangeViewModel { get; set; }
public Raw_Materials TargetMaterial { get; set; }
public ICommand RClickSwapCommand {get;set;}
public SwapMenuItem(Raw_Materials raw_Materials, ComponentChangeViewModel componentChangeViewModel)
{
ComponentChangeViewModel = componentChangeViewModel;
TargetMaterial = raw_Materials;
}
private void Swap()
{
//The command actually calls this method, but I excluded the long winded code
}
}
My problem is that the context menu does not appear when I right click the button, nothing happens at all. I am trying to work within the MVVM pattern, but am I missing some sort of event to make the context menu appear on right click? Most of the advice online does not use the context menu as part of Button.Resources
, but this seems to be the best way to do it according to some (for instance here). None of these examples contain anything to make the context menu appear on right click, so I figured it must be there by default?
Why can I not make the context menu appear, even when there are values in the ItemsSource
collection?