C#桌面开发之添加右键菜单

01—数据模型
这里模型比较简单,就定义一个学生类,定义三个属性,分别是id、姓名、性别,如下:这里重写了tostring方法,方便打印.

    [AddINotifyPropertyChangedInterface]    public class Students : PropertyChangedBase    {        private int id;        public int Id        {            get { return id; }            set            {                id = value;            }        }        public string Name { get; set; }
        private int age;        public int Age         {            get { return age; }            set            {                age = value;                if(age < 16 || age > 21 )                {                    AgeValidate = true;                }                else                {                    AgeValidate = false;                }            }        }
        public bool AgeValidate { get; set; }        public override string ToString()        {            StringBuilder report = new StringBuilder();            report.AppendLine($"[Id]  = [{Id}]");            report.AppendLine($"[Name]  = [{Name}]");            report.AppendLine($"[Age]  = [{Age}]");            report.AppendLine($"[AgeValidate]  = [{AgeValidate}]");            return report.ToString();        }    }

02—前台绑定

这里写了一个datagrid控件,然后菜单绑定ContextMenu="{Binding menu1}"

采用行选择的模式,如果要单元格选择模式这样操作:

 SelectionMode="Single" SelectionUnit="Cell"

右键事件绑定:

 cal:Message.Attach="[Event MouseRightButtonDown]=[datagrid_MouseRightButtonDown($source,$eventArgs)];" 
  <DataGrid Name="dgSourceData" AutoGenerateColumns="False" ItemsSource="{Binding StudentList}"                   ContextMenu="{Binding menu1}" RowHeaderWidth="30"  SelectedItem ="{Binding SelectedItems}"                                 cal:Message.Attach="[Event MouseRightButtonDown]=[datagrid_MouseRightButtonDown($source,$eventArgs)];"                                CellEditEnding="dgSourceData_BeginningEdit" SelectionChanged="dgSourceData_SelectionChanged" >            <DataGrid.Columns>                <DataGridTextColumn Header="Name"  Binding="{ Binding Path=Name}" MinWidth="68"/>                <DataGridTemplateColumn  Header="Age"  MinWidth="68" >                    <DataGridTemplateColumn.CellTemplate>                        <DataTemplate>                            <TextBox Text="{Binding Path=Age,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"                                      Foreground="{Binding AgeValidate,Converter={StaticResource ShowColorConverter}}" />                        </DataTemplate>                    </DataGridTemplateColumn.CellTemplate>                </DataGridTemplateColumn>                <DataGridTextColumn Header="Id"  Binding="{ Binding Path=Id}" MinWidth="48"/>            </DataGrid.Columns>        </DataGrid>

03—后台处理

   public System.Windows.Controls.DataGrid dGrid { get; set; }        public System.Windows.Controls.ContextMenu menu1 { get; set; }        public string BrowseDataSavePath { get; set; } = @"D:\Temporary";

后台逻辑很简单,感觉也没啥好讲的,详看代码,不懂得加我微信zls20210502咨询,或者来我技术群讨论

 /// <summary>        /// 右键删除数据        /// </summary>        /// <param name="sender">对象</param>        /// <param name="e">事件</param>        public void datagrid_MouseRightButtonDown(object sender, MouseButtonEventArgs e)        {            dGrid = (System.Windows.Controls.DataGrid)sender;            menu1 = new System.Windows.Controls.ContextMenu();            System.Windows.Controls.MenuItem menuitemFunc1 = new System.Windows.Controls.MenuItem();            System.Windows.Controls.MenuItem menuitemFunc2 = new System.Windows.Controls.MenuItem();            System.Windows.Controls.MenuItem menuitemFunc3 = new System.Windows.Controls.MenuItem();            menuitemFunc1.Header = "移动到此位置";            menuitemFunc2.Header = "删除此行信息";            menuitemFunc3.Header = "导出数据";            menuitemFunc1.Click += MoveToPostion_Click;            menuitemFunc2.Click += DeleteRow_Click;            menuitemFunc3.Click += ExportData_Click;            menu1.Items.Add(menuitemFunc1);            menu1.Items.Add(menuitemFunc2);            menu1.Items.Add(menuitemFunc3);            menu1.StaysOpen = true;        }        /// <summary>        /// 点击删除后的事件        /// </summary>        /// <param name="sender">对象</param>        /// <param name="e">事件</param>        public void DeleteRow_Click(object sender, RoutedEventArgs e)        {            StudentList.RemoveAt(dGrid.SelectedIndex);        }        /// <summary>        /// 移动到当前选定的位置        /// </summary>        /// <param name="sender">对象</param>        /// <param name="e">事件</param>        public void MoveToPostion_Click(object sender, RoutedEventArgs e)        {            try            {                //此方法省略;                System.Windows.MessageBox.Show("机台已成功移动到当前坐标");            }            catch (Exception ex)            {                Console.WriteLine(ex);            }        }        /// <summary>        /// 导出datagrid表格中的数据        /// </summary>        /// <param name="sender">对象</param>        /// <param name="e">事件</param>        public void ExportData_Click(object sender, RoutedEventArgs e)        {            BrowseSavePath();        }        /// <summary>        /// 导出地址浏览        /// </summary>        public void BrowseSavePath()        {            FolderBrowserDialog browserDialog = new FolderBrowserDialog();            browserDialog.Description = "请选择路径";            try            {                if (browserDialog.ShowDialog() == DialogResult.OK)                {                    if (string.IsNullOrEmpty(browserDialog.SelectedPath))                    {                        System.Windows.MessageBox.Show("文件夹路径不能为空");                        return;                    }                    BrowseDataSavePath = browserDialog.SelectedPath;                    DataExport(BrowseDataSavePath);                }            }            catch (Exception ex)            {                Console.WriteLine(ex);            }        }        public void DataExport(string path)        {            //此方法省略;            System.Windows.MessageBox.Show("数据已成功导出");        }

04—效果演示

C#桌面开发之添加右键菜单

05—源码下载

百度网盘下载链接:

https://pan.baidu.com/s/1pXr-uIa-MDpaOPeN0G0GVg   提取码:1314