【发布时间】:2014-06-26 17:31:14
【问题描述】:
所以我正在尝试使用 WPF 和 MVVM light 构建一个小型食谱应用程序。我遇到了将模型中的列表绑定到视图模型的情况。它可以很好地显示和删除项目,但是在添加项目时我无法更新显示。
我遇到了 ObserableCollections,这似乎正是我想要的,但我不确定我是否正确使用它们,因为每次都创建一个新的 OC 似乎是错误的。当模型使用列表时,我应该如何检索可观察的集合?
型号:
public class Recipe
{
public int Id { get; set; }
public string Title { get; set; }
public List<RecipeIngredient> Ingredients { get; set; }
}
public class RecipeIngredient
{
// ... //
}
视图模型:
public Recipe SelectedRecipe
{
get
{
return this.selectedRecipe;
}
set
{
this.selectedRecipe = value;
RaisePropertyChanged("SelectedRecipe");
RaisePropertyChanged("RecipeIngredients");
}
}
public ObservableCollection<RecipeIngredient> RecipeIngredients
{
get
{
return new ObservableCollection<RecipeIngredient>(selectedRecipe.Ingredients.ToList());
}
}
public RelayCommand<EventArgs> AddIngredientCommand { get; private set; }
public RelayCommand<string> DeleteIngredientCommand { get; private set; }
private void AddIngredient(EventArgs eventArgs)
{
SelectedRecipe.Ingredients.Add(new RecipeIngredient() { Name = "New Ingredient" });
RaisePropertyChanged("RecipeIngredients");
}
private void DeleteIngredient(string name)
{
SelectedRecipe.Ingredients = SelectedRecipe.Ingredients.Where(i => i.Name != name).ToList();
RaisePropertyChanged("RecipeIngredients");
}
public MainViewModel()
{
DBController db = new DBController();
recipes = db.GetRecipeList();
RecipeSelectionChangedCommand = new RelayCommand<SelectionChangedEventArgs>((args) => RecipeSelectionChanged(args));
SaveRecipeCommand = new RelayCommand<EventArgs>((args) => SaveRecipe(args));
AddIngredientCommand = new RelayCommand<EventArgs>((args) => AddIngredient(args));
DeleteIngredientCommand = new RelayCommand<string>((args) => DeleteIngredient(args));
}
我是不是跑偏了?
【问题讨论】:
-
为什么需要 ViewModel 中的 ObservableCollection 作为模型中的 List?
-
RecipeIngredients 只能在构造函数中实例化一次。否则,每次 UI 想要刷新它都会获得一个新实例。完全没有必要,而且可能导致不当行为。
-
MMVM Light 为已更改的属性提供 lambda 表达式:RaisePropertyChanged(() => this.RecipeIngredients),这使得它更安全、更易于重构和更易于维护。
-
哦,哇,感谢有关 lambda 的提示,重构绝对是一件痛苦的事。
-
@Tomtom - 因为我最初是绑定到 SelectedRecipe.Ingredients 的,但是删除列表并调用 RPC 永远不会刷新它,直到我创建了一个 OC 属性并绑定到它。
标签: c# wpf mvvm mvvm-light observablecollection