Xamarin形成MVVM Stacklayout内容绑定 [英] Xamarin forms MVVM Stacklayout content binding
本文介绍了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); }
}
}
这篇关于Xamarin形成MVVM Stacklayout内容绑定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文