Reputation: 1
I have been trying to write a virtual shop for a school project and have been having trouble converting the selected items into my Shoppingcart
list
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
{
}
}
Upvotes: 0
Views: 349
Reputation: 146
Bind the ListBox ItemsSource property to a list of shoppingCart items, and bind to the "IsSelected" property on each ListBox item.
Below is a simple example. The shopItems class has a "IsItemSelected" and "Name" property which are used for binding to the ListBox. When items are selected in the ListBox, the IsItemSelected property is set to 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>
Upvotes: 1