I have a listview in my TimePage xaml:
<ListView x:Name="moduleList" Width="1120" Height="231" Margin="42,536,186,217" Grid.Column="1" >
<ListView.View>
<GridView>
<GridViewColumn Header="Program Name" Width="160" DisplayMemberBinding="{Binding name}"/>
<GridViewColumn Header="Program Code" Width="160" DisplayMemberBinding="{Binding code}"/>
<GridViewColumn Header="Number of Credits" Width="160" DisplayMemberBinding="{Binding credits}"/>
<GridViewColumn Header="Number of Hours" Width="160" DisplayMemberBinding="{Binding hours}"/>
<GridViewColumn Header="Semester start date" Width="160" DisplayMemberBinding="{Binding date}"/>
<GridViewColumn Header="Semester Weeks" Width="160" DisplayMemberBinding="{Binding weeks}"/>
<GridViewColumn Header="Study Hours" Width="160" DisplayMemberBinding="{Binding studyhours}"/>
</GridView>
</ListView.View>
</ListView>
my values are being taken from myModule class and each variable is binded to a variable:
public string name { get; set; }
public string code { get; set; }
public int credits { get; set; }
public int hours { get; set; }
public string date { get; set; }
public int studyhours { get; set; }
public int weeks { get; set; }
I make use of this code in the TimePage.cs in order to allow me to add values into listView:
List<Modules> modules = new List<Modules>();
modules.Add(new Modules()
{
name = namebox.Text,
code = codebox.Text,
credits = int.Parse(0 creditbox.Text),
hours = int.Parse(0 hoursbox.Text),
date = semesterbox.Text,
weeks = int.Parse(0 semesterweekbox.Text),
studyhours = m1.Calculations(int.Parse(hoursbox.Text),
int.Parse(creditbox.Text),
int.Parse(semesterweekbox.Text)),
}) ;
The code works and it allows me to output values onto the list box it comes out like this:
However, when I try to input new values it does not output a new item rather it updates the information on the first item:
how do I make it add a new item instead of updating information?
CodePudding user response:
You need to create readonly field with an observable collection:
private readonly ObsrvableCollection<Modules> modules
= new ObservableCollection<Modules>();
Once, after initializing the XAML, assign the field value to the ListView source:
InitializeComponent();
moduleList.ItemsSource = modules;
After that, in the code, work only with the collection in the field. Leave the ListView UI alone.
modules.Add(new Modules()
{
name = namebox.Text,
code = codebox.Text,
credits = int.Parse(0 creditbox.Text),
hours = int.Parse(0 hoursbox.Text),
date = semesterbox.Text,
weeks = int.Parse(0 semesterweekbox.Text),
studyhours = m1.Calculations
(
int.Parse(hoursbox.Text),
int.Parse(creditbox.Text),
int.Parse(semesterweekbox.Text)
)
}
);