The ContextMenu
is placed within a Popup
which has its own visual tree.
As a result, the ContextMenu is not part of the visual tree and is not be able to resolve anything outside the ContextMenu popup.
To fix this, you could explicitly set the ItermsSource
property as shown below:
private void btn_Click(object sender, RoutedEventArgs e)
{
popup.ItemsSource = FavoriteProductCollectionViewModelIns;
popup.Visibility = Visibility.Visible;
popup.IsOpen = true;
}
Alternatively, you could use the Popup's PlacementTarget property as shown here.
XAML:
<Button
x:Name="FavoriteProductButton"
Width="30"
Height="30"
VerticalAlignment="Center"
Margin="1,5,0,5"
Click="btn_Click"
ContextMenuService.IsEnabled="false">
<Button.ContextMenu>
<ContextMenu x:Name="popup"
ItemsSource="{Binding FavoriteProductCollectionViewModelIns }"
DisplayMemberPath="Name"
DataContext="{Binding PlacementTarget.DataContext, RelativeSource={RelativeSource Mode=Self}}" />
</Button.ContextMenu>
</Button>
Code Behind:
using System.Collections.Generic;
using System.Windows;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
FavoriteProductCollectionViewModelIns = new List<FavoriteProductViewModel>
{
new FavoriteProductViewModel {Name = "Menu 1"},
new FavoriteProductViewModel {Name = "Menu 2"}
};
DataContext = this;
popup.PlacementTarget = FavoriteProductButton;
}
public class FavoriteProductViewModel
{
public string Name { get; set; }
}
public List<FavoriteProductViewModel> FavoriteProductCollectionViewModelIns { get; set; }
private void btn_Click(object sender, RoutedEventArgs e)
{
popup.Visibility = Visibility.Visible;
popup.IsOpen = true;
}
}