Xamarin形成MVVM Stacklayout内容绑定
问题描述:
我真的是Xamarin和Xamarin表格的新手,我需要一些帮助.
I'm really new to Xamarin and Xamarin forms and I need some help.
我有一个StackLayout,我想从ViewModel动态地向其中添加项目.问题是我似乎无法将StackLayout的内容绑定到ViewModel的StackLayout.
I have a StackLayout to which I want to add items dynamically from my ViewModel. Problem is I can't seem to bind the content of the StackLayout to my ViewModel's StackLayout.
这是我看来的xaml代码
this is my xaml code in my view
<StackLayout/>
我想要
<StackLayout Content="{Binding MainStackLayout}"/>
我已经在ViewModel中设置了这样的StackLayout
I have a StackLayout already setup in my ViewModel like this
public StackLayout MainStackLayout;
答
您必须编写一个UI组件.
You have to write a UI component.
using Xamarin.Forms;
using System.Collections.Specialized;
using System.ComponentModel;
class BindableStackLayout : StackLayout
{
public static readonly BindableProperty ItemsProperty =
BindableProperty.Create(nameof(Items), typeof(ObservableCollection<View>), typeof(BindableStackLayout), null,
propertyChanged: (b, o, n) =>
{
(n as ObservableCollection<View>).CollectionChanged += (coll, arg) =>
{
switch (arg.Action)
{
case NotifyCollectionChangedAction.Add:
foreach (var v in arg.NewItems)
(b as BindableStackLayout).Children.Add((View)v);
break;
case NotifyCollectionChangedAction.Remove:
foreach (var v in arg.NewItems)
(b as BindableStackLayout).Children.Remove((View)v);
break;
case NotifyCollectionChangedAction.Move:
//Do your stuff
break;
case NotifyCollectionChangedAction.Replace:
//Do your stuff
break;
}
};
});
public ObservableCollection<View> Items
{
get { return (ObservableCollection<View>)GetValue(ItemsProperty); }
set { SetValue(ItemsProperty, value); }
}
}