0

如果菜单项的数量大于 1,我想在鼠标左键单击按钮上调用 ContextMenu。这是我的 XAML:

<Button Content="Items" Click="Button_Click">
<Button.ContextMenu>
    <ContextMenu ItemsSource="{Binding Items}">
        <ContextMenu.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Name}"/>
            </DataTemplate>
        </ContextMenu.ItemTemplate>
    </ContextMenu>
</Button.ContextMenu></Button>

这是后面的代码:

 private void Button_Click(object sender, RoutedEventArgs e)
    {
        Button senderButton = sender as Button;
        if (senderButton == null) return;
        var items = senderButton.ContextMenu.Items;
        if (items.Count < 2) return;
        senderButton.ContextMenu.PlacementTarget = senderButton;
        senderButton.ContextMenu.IsOpen = true;
    }

问题是物品。计数始终等于 0,即使当我删除if (items.Count < 2) return;行时它也能很好地显示项目

4

0 回答 0