如何从 ViewModel 到 View 获取集合? [英] How to get a collection from the ViewModel to the View?
问题描述
我有一个 ObservableCollection
对象存储在 ViewModel
中,并且对于每个对象,我想将 BoxView
添加到我的 >查看代码>.我计划在后面的 XAML 代码中构建
BoxViews
以使其与业务逻辑分离.我的问题是我无法找出从 View
访问 ViewModel
中的集合的正确方法.有没有办法将 View
中的集合变量绑定到 ViewModel
中的一个,或者也许有人知道实现这样的东西的更好方法?
I have an ObservableCollection
of objects that gets stored in the ViewModel
and for each object I want to add a BoxView
to my View
. I plan to build the BoxViews
in the XAML code behind to keep it separate from the business logic. My problem is that I cannot figure out the correct way to access the collection in the ViewModel
from the View
. Is there a way to bind a collection variable in the View
to the one in the ViewModel
, or maybe someone knows a better way to implement something like this?
推荐答案
public partial class MyPage
{
private MyViewModel _viewModel;
public MyPage()
{
InitializeComponent();
}
protected override void OnBindingContextChanged()
{
base.OnBindingContextChanged();
_viewModel = BindingContext as MyViewModel;
var collection = _viewModel.MyCollection;
}
}
这篇关于如何从 ViewModel 到 View 获取集合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!