我正在为我的食谱应用程序编写一个成分计算器,该计算器从选择器中获取一个值,并将ObservableCollection中的成分数量更改为用户选择的人数。调试表明,后面的代码可以正常工作,但是可观察的集合不会用新值更新UI。请帮忙。
namespace SQLiteListView.Models
{
public class Ingredients : INotifyPropertyChanged
{
// primary key
[PrimaryKey, AutoIncrement]
public int IngredientsId { get; set; }
// other attributes
private string _ingredientsName { get; set; }
private double _ammount { get; set; }
private string _units { get; set; }
public string IngredientsName
{
get { return _ingredientsName; }
set
{
_ingredientsName = value;
OnPropertyChange("IngredientsName");
}
}
public double Ammount
{
get { return _ammount; }
set
{
_ammount = value;
OnPropertyChange("ammount");
}
}
public string Units
{
get { return _units; }
set
{
_units = value;
OnPropertyChange("Units");
}
}
public int RecipeID
{
get { return _recipeID; }
set
{
_recipeID = value;
OnPropertyChange("RecipeID");
}
}
// specify the foreign key
[ForeignKey(typeof(Recipe))]
public int _recipeID { get; set; }
// many to one relationship with recipe
[ManyToOne]
public Recipe Recipe { get; set; }
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChange(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
ViewModel
private PickerNo _selectedPicker { get; set; }
public PickerNo SelectedPicker
{
get { return _selectedPicker; }
set
{
_selectedPicker = value;
IngredientsCalculator();
}
}
void IngredientsCalculator()
{
var ingredients = new ObservableCollection<Ingredients>();
foreach (Ingredients i in IngredientsList)
{
i.Ammount = (i.Ammount / Recipe.Serves) * SelectedPicker.NumberOfPeople;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string PropertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(PropertyName));
}