我想从视图中的输入字段中获取数据并存储它,以便我可以在我的数据库中创建一个对象的新实例并将其显示在列表视图中。到目前为止,我已经设法从输入字段中获得了一个成分名称。它显示在下面的标签中,因此它必须发生。但是当我尝试将其添加到成分实例时,它说成分名称 = null。我不知道该怎么办。
<StackLayout Orientation="Horizontal">
<Label Text="Your Ingredient is:" />
<Label Text="{Binding IngredientName}" />
</StackLayout>
<Button x:Name="IngrediantsButton"
Text="Add Ingredient"
Command="{Binding Path=NewIngredientCommand, Source={StaticResource viewModel}}"/>
<ListView x:Name="IngredientsListView" ItemsSource="{Binding Ingredients, Source={StaticResource viewModel}}">
<ListView.ItemTemplate>
<DataTemplate>
<ViewCell>
<StackLayout Orientation="Horizontal">
<Label Text="{Binding IngredientsName}"/>
<Label Text="{Binding Ammount}"/>
<Label Text="{Binding Units}"/>
<Label Text="{Binding RecipeId}"/>
</StackLayout>
</ViewCell>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackLayout>
视图模型
private string _ingredientName { get; set; }
public string IngredientName
{
get
{
return _ingredientName;
}
set
{
if (_ingredientName != value)
{
_ingredientName = value;
OnPropertyChanged("IngredientName");
}
}
}
public Command NewIngredientCommand
{
get
{
return new Command(() =>
{
Ingredients ingredients = new Ingredients()
{
IngredientsName = IngredientName,
Ammount = 0,
Units = "g",
RecipeId = Recipe1.RecipeID,
Recipe = Recipe1
};
Ingredients.Add(ingredients);
});
}
}
protected virtual void OnPropertyChanged(string propertyName)
{
var changed = PropertyChanged;
if (changed != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
private ICommand _saveIngredientCommand;
public ICommand SaveIngredientCommand => _saveIngredientCommand ?? (_saveIngredientCommand = new Command(() =>
{
Ingredients ingredient = new Ingredients();
App.RecipeDbcontroller.SaveIngredients(ingredient);
if (Ingredient.IngredientsName != null && Ingredient.Ammount != 0)
{
ingredient.IngredientsName = Ingredient.IngredientsName;
ingredient.Ammount = Ingredient.Ammount;
ingredient.Units = Ingredient.Units;
ingredient.Recipe = Recipe;
ingredient.RecipeID = Recipe.RecipeID;
App.RecipeDbcontroller.SaveIngredients(ingredient);
IngredientsList.Add(ingredient);
Recipe.Ingredients.Add(ingredient);
IngredientMessage = "Your ingredient has been added";
}
else
{
IngredientMessage = "Please add at least one ingredient";
App.RecipeDbcontroller.DeleteIngredients(ingredient.IngredientsId);
}