让视图模型向其视图添加子项是否正确?
Is it correct to let the viewmodel add children to its view?
我目前正在学习 WPF 中的 MVVM 模式。我认为这真的很酷,但我的问题是:直接使用视图模型将子项附加到其视图是否正确?
例如,假设我们有一个方法,其中包含一个循环,该循环在单击按钮时将新行添加到网格。我的 ViewModel 应该只包含纯数据还是可以包含在字段上放置新元素的逻辑?以及删除它们。
is it correct to use the viewmodel directly for appending children to its view?
没有。视图模型不应该知道任何视图元素。
Should my ViewModel only contain pure data or can it also contain logic for placing new elements on the field? As well as removing them.
前者。视图模型可能会公开视图恰好在 Grid
中显示的数据对象集合。或者其他类型的面板。视图模型不关心哪个。
您通常会在视图中使用 ItemsControl
来显示视图模型集合中的项目,即 ItemsControl
绑定到源集合并显示每个项目的可视化表示面板。
我目前正在学习 WPF 中的 MVVM 模式。我认为这真的很酷,但我的问题是:直接使用视图模型将子项附加到其视图是否正确?
例如,假设我们有一个方法,其中包含一个循环,该循环在单击按钮时将新行添加到网格。我的 ViewModel 应该只包含纯数据还是可以包含在字段上放置新元素的逻辑?以及删除它们。
is it correct to use the viewmodel directly for appending children to its view?
没有。视图模型不应该知道任何视图元素。
Should my ViewModel only contain pure data or can it also contain logic for placing new elements on the field? As well as removing them.
前者。视图模型可能会公开视图恰好在 Grid
中显示的数据对象集合。或者其他类型的面板。视图模型不关心哪个。
您通常会在视图中使用 ItemsControl
来显示视图模型集合中的项目,即 ItemsControl
绑定到源集合并显示每个项目的可视化表示面板。