0

I want to show Context menu on button click so I did the following

<Button Grid.Row="0" 
        Grid.Column="4" 
        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"/>
            </Button.ContextMenu>
</Button>/

private void btn_Click(object sender, RoutedEventArgs e)
{
    popup.Visibility = Visibility.Visible;
    popup.IsOpen = true;
}

The problem the binding doesn't work and the context is empty, any idea how to fix the binding issue?

Taterhead
  • 5,763
  • 4
  • 31
  • 40
AMH
  • 6,363
  • 27
  • 84
  • 135

1 Answers1

2

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;
    }
}
Community
  • 1
  • 1
Jamleck
  • 1,017
  • 7
  • 12