如何从模型添加复选框到stacklayout

时间:2018-01-22 13:29:38

标签: xaml xamarin xamarin.forms xamarin.ios xamarin.android

我有一个视图(xaml),其中包含一个带有id" CheckBoxList"的stacklayout。从viewmodel我想为这个stacklayout添加一些复选框。但我不知道怎么做。我无法使用

CheckBoxList.Children.Add(checkbox);

有一种简单的方法吗?

感谢

1 个答案:

答案 0 :(得分:0)

  

我有一个视图(xaml),其中包含一个id为“CheckBoxList”的stacklayout。从viewmodel我想为这个stacklayout添加一些复选框。但我不知道如何。

不推荐,但这可能是一种方式:您可以将整个StackLayout(CheckBoxList)绑定到ContentView.Content

  1. 在ViewModel中定义CheckBoxList:

    public class MainPageViewModel
    {
        public StackLayout CheckBoxList { get; set; }
        public MainPageViewModel()
        {
            //You can modify the codes as you want
            CheckBoxList = new StackLayout();
            for (int i = 0; i < 30; i++)
            {
                CheckBoxList.Children.Add(new MyCheckBox { IsChecked = i % 2 == 1 ? true : false });
            }
        }
    }
    
  2. 在你的xaml中使用ContentView并绑定CheckBoxList

    <StackLayout x:Name="root">
        <ContentView Content="{Binding CheckBoxList}"></ContentView>
    </StackLayout>
    
  3. 将viewmodel绑定在代码后面:

    public partial class MainPage : ContentPage
    {
    
        MainPageViewModel ViewModel { get; set; }
        public MainPage()
        {
            InitializeComponent();
            ViewModel = new MainPageViewModel();
            this.BindingContext = ViewModel;
        }
    }
    

    以下是完整的demo