我对 Xamarin 和 Xamarin 表单非常陌生,我需要一些帮助。
我有一个 StackLayout,我想从 ViewModel 动态添加项目。问题是我似乎无法将 StackLayout 的内容绑定到 ViewModel 的 StackLayout 。
在我看来,这是我的 xaml 代码
<StackLayout/>
我想要类似的东西
<StackLayout Content="{Binding MainStackLayout}"/>
我的 ViewModel 中已经设置了 StackLayout,如下所示
public StackLayout MainStackLayout;
您必须编写一个 UI 组件。
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); }
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)