i m trying to do a project with mvvm xamarin.
I have a listview ( bounded a observablecollection), and inside the listview, i have a button. with clicking this button, i make some updates in Observable collection. But the updates, doesnt effect untill i remove and again insert the Observable collection.
here is the code
<ListView ItemsSource="{Binding SalesList,Mode=TwoWay}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell IsEnabled="True" >
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label FontSize="Large" Text="{Binding StockTotal}"/>
<Button Text="+" Grid.Column="1" CommandParameter="{Binding .}" Command="{Binding Path=BindingContext.ADDOPERATION, Source={x:Reference Mypage}}" />
<Entry Text="{Binding StockAmount}" Grid.Column="2" />
</Grid>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
<Label Text="{Binding SUMMARY}"/>
public ICommand ADDOPERATION { get; set; }
public HomeVM()
{
SalesList.Add(new SalesModel { StockAmount = 1 });
SalesList.Add(new SalesModel { StockAmount = 2 });
SalesList.Add(new SalesModel { StockAmount = 3 });
ADDOPERATION = new Command(MYADDOPERATION);
}
private void MYADDOPERATION(object obj)
{
if (obj == null) return;
var cominginfo = (SalesModel)obj;
var index= SalesList.IndexOf(cominginfo);
cominginfo.StockAmount++;
cominginfo.StockTotal = cominginfo.StockAmount * 55;
}
private double _SUMMARY;
public double SUMMARY
{
get { return SalesList.Sum(c => c.StockTotal); }
set
{
_SUMMARY = SalesList.Sum(c=>c.StockTotal);
INotifyPropertyChanged();
}
}
I don't know why this problem is occured. the ADDOPERATION command works successfuly ( i checked it in debuge mode), but it doesnt update the listview. List view updates when i add this code to below. But i think i m missing something, because, when ever i make changes inside the ObservableCollection, it should automaticly effect the UI. I m able to do it only after i remove and again insert the same data.
SalesList.RemoveAt(index);
SalesList.Insert(index, cominginfo);
the BaseViewModel class for INotifyPropertyChanged event
public class BaseViewModel : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void INotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
my model class
public class SalesModel:BaseViewModel
{
public double StockTotal { get; set; }
public string StockName { get; set; }
public double StockAmount { get; set; }
}
Thanks in advance
SalesModel
needs to implement INotifyPropertyChanged. ObservableCollection only handles additions and changes to the collection, not changes to properties of items that are in the collection. – Jason