WPF右键弹出菜单(ContextMenu的应用)
程序员文章站
2022-07-13 21:47:54
...
例子1:
<RichTextBox>
<RichTextBox.ContextMenu>
<ContextMenu>
<MenuItem Command="Cut">
<MenuItem.Icon>
<Image Source="Images/cut.png" />
</MenuItem.Icon>
</MenuItem>
<MenuItem Command="Copy">
<MenuItem.Icon>
<Image Source="Images/copy.png" />
</MenuItem.Icon>
</MenuItem>
<MenuItem Command="Paste">
<MenuItem.Icon>
<Image Source="Images/paste.png" />
</MenuItem.Icon>
</MenuItem>
<MenuItem header="111111" click=”xxxxx”> </MenuItem>
</ContextMenu>
</RichTextBox.ContextMenu></RichTextBox>
例子2:
<DataTemplate>
<Grid Tag="{Binding DataContext, RelativeSource={RelativeSource AncestorType={x:Type ListBox}}}">
<Grid.ContextMenu>
<ContextMenu DataContext="{Binding Path=PlacementTarget.Tag, RelativeSource={RelativeSource Self}}">
<MenuItem Content="Cut" Command="{Binding CutCommand}" />
<MenuItem Content="Copy" Command="{Binding CopyCommand}" />
<MenuItem Content="Paste" Command="{Binding PasteCommand}" />
</ContextMenu>
</Grid.ContextMenu>
</Grid>
</DataTemplate>
例子3: 点击按钮,出现菜单
<Window x:Class="WpfTutorialSamples.Common_interface_controls.ContextMenuManuallyInvokedSample"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="ContextMenuManuallyInvokedSample" Height="250" Width="250">
<Window.Resources>
<ContextMenu x:Key="cmButton">
<MenuItem Header="Menu item 1" />
<MenuItem Header="Menu item 2" />
<Separator />
<MenuItem Header="Menu item 3" />
</ContextMenu>
</Window.Resources>
<Grid>
<Button Content="Click me!" VerticalAlignment="Center" HorizontalAlignment="Center" Click="Button_Click" />
</Grid>
</Window>
using System;
using System.Windows;
using System.Windows.Controls;
namespace WpfTutorialSamples.Common_interface_controls
{
public partial class ContextMenuManuallyInvokedSample : Window
{
public ContextMenuManuallyInvokedSample()
{
InitializeComponent();
}
private void Button_Click(object sender, RoutedEventArgs e)
{
ContextMenu cm = this.FindResource("cmButton") as ContextMenu;
cm.PlacementTarget = sender as Button;
cm.IsOpen = true;
}
}
}
效果如下图:
例子4: 绑定listbox中的元素
<ListBox Name="ListboxDisplay" Height="220" Margin="16,213,351,0" VerticalAlignment="Top">
<ListBox.ContextMenu>
<ContextMenu DataContext="Binding ElementName=ListboxDisplay, Path=SelectedItems">
<MenuItem Header="write epc" Click="menu_write_epc" ToolTip="" ></MenuItem>
<MenuItem Header="write tid" Click="menu_write_tid" ToolTip=""></MenuItem>
<MenuItem Header="write user" Click="menu_write_user" ToolTip=""></MenuItem>
<MenuItem Header="lock" Click="menu_lock" ToolTip=""></MenuItem>
</ContextMenu>
</ListBox.ContextMenu>
</ListBox>
推荐阅读
-
Win10右键菜单弹出很慢怎么办?Win10右键弹出菜单卡顿的解决方法
-
Win10右键菜单弹出很慢怎么办?Win10右键弹出菜单卡顿的解决方法
-
vue2.0的contextmenu右键弹出菜单的实例代码
-
WPF 右键菜单ContextMenu
-
WPF中鼠标右键菜单栏实现(ContextMenu)
-
WPF右键弹出菜单(ContextMenu的应用)
-
WPF解决ContextMenu菜单的DataContext无法绑定,并实现按钮左键弹出菜单
-
WPF ContextMenu右键菜单和控件的DataContext进行绑定的最佳实践
-
Android中实现长按照片弹出右键菜单功能的实例代码
-
WPF中的右键菜单.