绑定按钮上下文菜单

Bind Button ContextMenu

我想在单击按钮时显示上下文菜单,所以我执行了以下操作

<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;
}

绑定不起作用且上下文为空的问题,知道如何解决绑定问题吗?

ContextMenu 放置在 Popup 中,它有自己的可视化树。

因此,上下文菜单不是可视化树的一部分,无法解析上下文菜单弹出窗口之外的任何内容。

要解决此问题,您可以显式设置 ItermsSource 属性,如下所示:

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

或者,您可以使用 Popup 的 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>

隐藏代码:

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;
    }
}