我有一個ListBox的元素,我需要顯示的元素,我有工作,但我想添加一個選項來刪除選定的項目,這裏是問題...我刪除它,但我是從列表框中刪除而不是從元素類,我能做些什麼來從樹中刪除項目?這裏是我的代碼:複合設計模式
表1:
private void btnBuildPartsList_Click(object sender, EventArgs e)
{
Assembly topWidget = new Assembly("Main Assembly", 1);
Assembly chassis = new Assembly("Chassis", 1);
Assembly display = new Assembly("Display", 1);
Assembly powerSupply = new Assembly("Power Supply", 1);
Part bolt = new Part("Bolt", 24);
Part mainCase = new Part("Case", 1);
Part screen = new Part("Screen", 3);
Part displayElectronics = new Part("Display Electronics", 3);
Part transformer = new Part("Transformer", 1);
Part powerBoard = new Part("Power Board", 1);
Part ductTape = new Part("Duct Tape", 5);
Part gum = new Part("Bubble Gum", 25);
topWidget.Add(chassis);
topWidget.Add(display);
topWidget.Add(powerSupply);
chassis.Add(mainCase);
chassis.Add(bolt);
display.Add(screen);
display.Add(displayElectronics);
powerSupply.Add(transformer);
powerSupply.Add(powerBoard);
topWidget.Add(ductTape);
topWidget.Add(gum);
DisplayPartsList(topWidget);
}
private void DisplayPartsList(Assembly topWidget)
{
List<string> partsList = new List<string>();
topWidget.WritePartsList(partsList);
listParts.Items.Clear();
listParts.Items.AddRange(partsList.ToArray());
}
,這裏是我的組裝類:
namespace Composite
{
public class Assembly : BaseAssembly
{
private List<BaseAssembly> elements = new List<BaseAssembly>();
public Assembly(string name, int quantity)
: base(name, quantity)
{
}
public override void Add(BaseAssembly assembly)
{
elements.Add(assembly);
}
public override void Remove(BaseAssembly assembly)
{
elements.Remove(assembly);
}
public override void WritePartsList(List<string> list)
{
list.Add(Quantity.ToString() + " - " + Name);
foreach (BaseAssembly assembly in elements)
{
assembly.WritePartsList(list);
}
}
}
}
我認爲這個代碼就足夠了,其他所有的代碼,它就像在其它複合設計模式代碼,現在,我該如何去除項目功能?從我的列表框中選擇x
元素。就像我在從the listbox
中刪除該項目之前所說的,但我想從全班級中刪除它。提前致謝。
[連接列表到列表框](https://stackoverflow.com/questions/33623991/connect-listt-to-a-listbox) –
@RezaAghaei好吧,我明白,但我不明白如何將該代碼應用於我的項目,你能解釋我的方法嗎?我真的在努力,但我不知道該怎麼做 – User1899289003