我想知道如何正确地填充表单中的标签,其中包含“右键单击”中所选预设项目的信息。上下文菜单?我目前正在使用'名称'填充上下文菜单。每个班级'产品'。我想填写与用户右键菜单选择的项目对应的标签。当项目添加到列表中时,上下文菜单项将动态更改。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace rcMenu
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Product newProductA = new Product();
newProductA.Name = "Ice Cream";
newProductA.Category = "Dessert";
newProductA.Price = "Free";
productList.Add(newProductA);
Product newProductB = new Product();
newProductB.Name = "Cherries";
newProductB.Category = "Produce";
newProductB.Price = "$10.00";
productList.Add(newProductB);
Product newProductC = new Product();
newProductC.Name = "Soda";
newProductC.Category = "Beverage";
newProductC.Price = "$1.99";
productList.Add(newProductC);
}
public static List<Product> productList = new List<Product>();
public class Product
{
public String Name { get; set; }
public String Category { get; set; }
public String Price { get; set; }
}
private void SelectedPreset(object sender, EventArgs e)
{
label1.Text = "Product Name: " + "SELECTED";
label2.Text = "Product Category: " + "SELECTED";
label3.Text = "Product Price: " + "SELECTED";
}
private void contextMenuStrip1_Opened(object sender, EventArgs e)
{
(contextMenuStrip1.Items[0] as ToolStripMenuItem).DropDownItems.Clear();
foreach (var p in productList)
{
var itemName = p.Name;
(contextMenuStrip1.Items[0] as ToolStripMenuItem).DropDownItems.Add(itemName, null, SelectedPreset);
}
}
}
}
答案 0 :(得分:1)
首先订阅Opening事件并将代码放置如下:
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
{
if(contextMenuStrip1.Items.Count > 0)
contextMenuStrip1.Items.Clear();
foreach (var p in productList)
{
var itemName = p.Name;
contextMenuStrip1.Items.Add(itemName);
}
e.Cancel = false;
}
接下来订阅ItemClicked事件并放置如下代码:
private void contextMenuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
{
Product p = productList.Find(i => i.Name == e.ClickedItem.Text);
//just in case its null...
if(p != null)
{
label1.Text = "Product Name: " + p.Name;
label2.Text = "Product Category: " + p.Category;
label3.Text = "Product Price: " + p.Price;
}
}
答案 1 :(得分:0)
试试这个!
private void SelectedPreset(object sender, EventArgs e)
{
var p = productList.Where(x => x.Name == (sender as ToolStripMenuItem).Text).Single();
label2.Text = "Product Category: " + (sender as ToolStripMenuItem).Text;
label3.Text = "Product Price: " + p.Price;
}
你必须加油一点,加上适当的验证