Xamarin形成MVVM Stacklayout内容绑定

时间:2016-12-25 15:31:03

标签: c# mvvm xamarin.forms

我是Xamarin和Xamarin表格的新手,我需要一些帮助。

我有一个StackLayout,我想从我的ViewModel动态添加项目。问题是我似乎无法将StackLayout的内容绑定到我的ViewModel的StackLayout。

这是我视图中的xaml代码

<StackLayout/>

我想要像

这样的东西
<StackLayout Content="{Binding MainStackLayout}"/>

我已经在我的ViewModel中设置了StackLayout,就像这样

public StackLayout MainStackLayout;

3 个答案:

答案 0 :(得分:12)

您必须编写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); }
    }
}

答案 1 :(得分:2)

希望为您的stacklayout提供不同大小的可绑定项目源我自定义内容视图将帮助您实现它:)

String hexColor = String.format("#%06X", (0xFFFFFF & colorId));
  

here

下载源代码

答案 2 :(得分:0)

只需使用BindableLayout:https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/layouts/bindable-layouts

<StackLayout BindableLayout.ItemsSource="{Binding Items}">
    <BindableLayout.ItemTemplate>
        <DataTemplate>
            <Label Text="{Binding Title}" />
        </DataTemplate>
    </BindableLayout.ItemTemplate>
</StackLayout>

它支持ItemsSource,ItemTemplate和ItemTemplateSelector。