我有以下xaml,它定义了wpf:
中的contextmenu<Grid Name="grid">
<Button x:Name="settingsButton" DockPanel.Dock="Left" Content="Settings" Click="SettingsButtonClicked">
<Button.ContextMenu>
<ContextMenu>
<MenuItem Header ="Column Chooser">
<MenuItem IsCheckable="true" Header="A" IsChecked="{Binding Path=IsAChoosen}"></MenuItem>
<MenuItem IsCheckable="true" Header="B" IsChecked="{Binding Path=IsBChoosen}"></MenuItem>
<MenuItem IsCheckable="true" Header="C" IsChecked="{Binding Path=IsCChoosen}"></MenuItem>
</MenuItem>
</ContextMenu>
</Button.ContextMenu>
</Button>
</Grid>
如果我通过右键单击正常显示上下文菜单,则绑定工作正常。
但是我希望在我左键单击按钮而不是右键单击时显示上下文菜单。所以我有以下代码来执行此操作:
public partial class SettingsView : UserControl
{
public SettingsView()
{
InitializeComponent();
settingsButton.MouseRightButtonDown += SettingsButtonOnMouseRightButtonDown;
}
private void SettingsButtonOnMouseRightButtonDown(object sender, MouseButtonEventArgs mouseButtonEventArgs)
{
settingsButton.ContextMenu.Visibility = Visibility.Hidden;
}
private void SettingsButtonClicked(object sender, RoutedEventArgs e)
{
settingsButton.ContextMenu.Visibility = Visibility.Visible;
settingsButton.ContextMenu.PlacementTarget = sender as Image;
settingsButton.ContextMenu.IsOpen = true;
}
}
当我这样做时,绑定不起作用。任何人都知道为什么它可以通过右键单击而不是当我强制它左键单击?
答案 0 :(得分:3)
而不是Image将PlacementTarget设置为Button
private void SettingsButtonClicked(object sender, RoutedEventArgs e)
{
settingsButton.ContextMenu.Visibility = Visibility.Visible;
settingsButton.ContextMenu.PlacementTarget = sender as Button;
settingsButton.ContextMenu.IsOpen = true;
}