我已经完成了之前的一些类似问题,但我仍然遇到ContextMenuService.Placement的问题。请建议。
当我遵循这种方法时,它运作良好
<Button x:Name="btn" Content="button" Click="b_Click" >
<Button.ContextMenu >
<ContextMenu >
<MenuItem Header="Open" Command="{Binding OnOpen}" ></MenuItem>
<MenuItem Header="Close" Command="{Binding OnClose}"></MenuItem>
</ContextMenu>
</Button.ContextMenu>
</Button>
private void be_Click(object sender, RoutedEventArgs e)
{
btn.ContextMenu.PlacementTarget = btn;//Like this
btn.ContextMenu.Placement = PlacementMode.Top;//Like this
btn.ContextMenu.DataContext = btn.DataContext;
btn.ContextMenu.IsOpen = true;
}
但它不适用于MVVM模式。
<Button x:Name="btn" VerticalAlignment="Bottom" ContextMenuService.IsEnabled="False">
<Button.Style>
<Style TargetType="{x:Type Button}" BasedOn="{StaticResource {x:Type Button}}">
<Style.Triggers>
<EventTrigger RoutedEvent="Click">
<EventTrigger.Actions>
<BeginStoryboard>
<Storyboard>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsOpen">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
<BooleanAnimationUsingKeyFrames Storyboard.TargetProperty="ContextMenu.IsEnabled">
<DiscreteBooleanKeyFrame KeyTime="0:0:0" Value="True"/>
</BooleanAnimationUsingKeyFrames>
</Storyboard>
</BeginStoryboard>
</EventTrigger.Actions>
</EventTrigger>
</Style.Triggers>
<Setter Property="ContextMenu">
<Setter.Value>
<ContextMenu Name="AddReportContextMenu" HorizontalAlignment="Right">
<MenuItem Header="Open" Command="{Binding OnOpen}" ></MenuItem>
<MenuItem Header="Close" Command="{Binding OnClose}"></MenuItem>
</ContextMenu>
</Setter.Value>
</Setter>
</Style>
</Button.Style>
</Button>
我尝试在像这样的setter中添加它
<Setter Property="ContextMenu.PlacementTarget" Value="{Binding ElementName=btn}"></Setter>
<Setter Property="ContextMenu.Placement" Value="Top"></Setter>
或者像这样:
<Setter Property="ContextMenuService.Placement" Value="Top"></Setter>
如果ContextMenuService.IsEnabled未设置为false,则右键单击此处的放置属性效果很好。我必须将其设置为false以确保ContextMenu仅适用于左键单击。
<Button x:Name="btn" ContextMenuService.Placement="Top">
谢谢!