2017-10-14 128 views
0

我一直想寫一個虛擬店一所學校的項目,並已遇到問題轉換所選項目到我Shoppingcart清單選擇列表框項目轉換成一個列表C#

public class shoppingcart 
    { 
     public int cost; 
     public int id; 
     public string name; 

     public void setCost(int c) 
     { 
      cost = c; 
     } 
     public void setId(int i) 
     { 
      id = i; 
     } 
     public void setname(string n) 
     { 
      name = n; 
     } 

     public void getCost(int c) 
     { 

     } 

     public void getId(int i) 
     { 

     } 

     public void getname(string n) 
     { 

     } 
    } 
    public List<shoppingcart> Shoppingcart = new List<shoppingcart>(); 
    //An example of what my objects look like incase this helps 
    //Experiment 
     shoppingcart ghostitem = new shoppingcart(); 
     ghostitem.setname(""); 
     ghostitem.setCost(0); 
     ghostitem.setId(0); 
     Shoppingcart.Add(ghostitem); 

    private void addCart_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      totalitems = totalitems + 1; 
      for (int i = 0; i < MeleeItem.Count(); i++) 
      { 
       Shoppingcart.Add(meleeList.SelectedItems); 
      } 
     } 
     catch 
     { 

     } 
    } 
+0

你在列表框中顯示? –

+0

您是否嘗試調試並查看以下類型:meleeList.SelectedItems – iYonatan

+0

列表框顯示對象的名稱。我希望能夠將所選對象轉移到購物車列表中,然後查找我爲特定對象設置的成本 – Firelord190

回答

0

綁定ListBox ItemsSource屬性添加到shoppingCart項目列表中,並綁定到每個ListBox項目上的「IsSelected」屬性。

下面是一個簡單的例子。 shopItems類具有用於綁定到ListBox的「IsItemSelected」和「Name」屬性。在列表框中選擇項目時,IsItemSelected屬性設置爲true。

public partial class MainWindow : Window 
    { 
     List<shopItems> availableItems; 
     public List<shopItems> AvailableItems 
     { 
      get 
      { 
       return availableItems; 
      } 
      set 
      { 
       availableItems = value; 
      } 
     } 

     public MainWindow() 
     { 
      InitializeComponent(); 
      DataContext = this; 
      availableItems = new List<shopItems> { new shopItems { Name = "Item 1" }, new shopItems { Name = "Item 2" } }; 
     } 

     public class shopItems 
     { 
      private string name; 
      public string Name 
      { 
       get 
       { 
        return name; 
       } 
       set 
       { 
        name = value; 
       } 
      } 

      private bool isItemSelected = false; 
      public bool IsItemSelected 
      { 
       get 
       { 
        return isItemSelected; 
       } 
       set 
       { 
        isItemSelected = value; 
       } 
      } 
     } 
    } 

XAML:

<ListBox ItemsSource="{Binding AvailableItems}" SelectionMode="Multiple" DisplayMemberPath="Name"> 
    <ListBox.ItemContainerStyle> 
     <Style TargetType="ListBoxItem"> 
      <Setter Property="IsSelected" Value="{Binding IsItemSelected}"/> 
     </Style> 
    </ListBox.ItemContainerStyle> 
</ListBox> 
+0

我可以獲得一些示例代碼嗎? – Firelord190

+0

我編輯了我的回覆以包含一個簡單的例子 - 希望這有助於。 – AlBal