[英]Converting selected listbox items into a list C#
我一直在嘗試為學校項目編寫虛擬商店,並且在將所選商品轉換為我的Shoppingcart
列表時遇到麻煩
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
{
}
}
將ListBox ItemsSource屬性綁定到shoppingCart項目列表,並綁定到每個ListBox項目上的“ IsSelected”屬性。
以下是一個簡單的示例。 shopItems類具有“ IsItemSelected”和“ Name”屬性,用於綁定到ListBox。 在列表框中選擇項目時,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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.