06
2014
06

Silverlight 5 右键菜单ContextMenu 的实现方法

 


一、 安装 silverlight5 toolkit

http://silverlight.codeplex.com/releases

然后引用 程序集 System.Windows.Controls.Input.Toolkit.dll

<Grid x:Name="LayoutRoot" Background="White" MouseRightButtonDown="LayoutRoot_MouseRightButtonDown">
        <Button Content="右键菜单" Height="23" HorizontalAlignment="Left" Margin="10,10,0,0" Name="btnRight" VerticalAlignment="Top" Width="75" />
</Grid>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace RightMenu
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            BindMenu();
        }
        private void BindMenu()
        {
            ContextMenu cm = new ContextMenu();//新建右键菜单
            MenuItem mi = new MenuItem();//新建右键菜单项
            mi.Header = "菜单项";
            mi.Click += new RoutedEventHandler(mi_Click);//为菜单项注册事件
            cm.Items.Add(mi);
            ContextMenuService.SetContextMenu(btnRight, cm);//为控件绑定右键菜单
        }
        void mi_Click(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("右键菜单事件");
        }
        private void LayoutRoot_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            e.Handled = true; //屏蔽默认的右键菜单
        }
    }
}

 

二、在没有安装toolkit 的情况下也可以自己写右键菜单

实例如下:

 

 

ContentMenuDemo.zip

« 上一篇下一篇 »

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。