Xamarin - 在xaml中绑定视图模型

时间:2017-01-19 09:08:27

标签: c# xaml xamarin.android xamarin.forms

我将分组列表视图绑定到通过xaml查看模型数据源。 但是当应用程序启动时,即使我从ctor后面的代码填充它,列表也是空的。当我声明ListView x:Name =“myList”并从后面的代码填充它时,它可以工作,但它不会直接“绑定”到视图模型。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewModels="clr-namespace:Atc.Obedy.ViewModels;assembly=Atc.Obedy"
             x:Class="Atc.Obedy.MainPage" Title="Jídelníček">
  <ContentPage.Padding>
    <OnPlatform x:TypeArguments="Thickness"
                iOS="20, 40, 20, 20"
                Android="20, 20, 20, 20"
                WinPhone="20, 20, 20, 20" />
  </ContentPage.Padding>

  <ContentPage.BindingContext>
    <viewModels:MainPageViewModel />
  </ContentPage.BindingContext>

  <ContentPage.Content>
    <StackLayout VerticalOptions="FillAndExpand"
                 HorizontalOptions="FillAndExpand"
                 Orientation="Vertical"
                 Spacing="15">
      <ListView BindingContext="{ Binding MealsGroups }"  GroupDisplayBinding="{ Binding DisplayName }" IsGroupingEnabled="true">
        <ListView.ItemTemplate>
          <DataTemplate>
            <ViewCell>
                <StackLayout Orientation="Vertical">
                  <StackLayout Orientation="Horizontal">
                  <Label Text="{Binding MealTitle}" />
                    <Button Image="icon.png" Command="{ Binding OrderCommand }" />
                </StackLayout>
              </StackLayout>
            </ViewCell>
          </DataTemplate>
        </ListView.ItemTemplate>
      </ListView>
    </StackLayout>
  </ContentPage.Content>
</ContentPage>

代码背后:

public partial class MainPage : ContentPage
    {
        protected IMealsRepository MealsRepository { get; }

        public MainPage()
        {
            MealsRepository = IoC.Container.Get<IMealsRepository>();

            var mealGroups = new ObservableCollection<MealsGroup>();

            foreach (var meals in MealsRepository.GetMeals(DateTime.MinValue, DateTime.MaxValue).Where(x => x.DayOfOrder != null).GroupBy(x=>x.DayOfOrder))
            {
                mealGroups.Add(ProvideMealsGroup(meals.Key.Value, meals));
            }
            InitializeComponent();

            var viewModel = BindingContext as MainPageViewModel;



            viewModel.MealsGroups = mealGroups;
        }

这是视图模型:

public class MainPageViewModel : INotifyPropertyChanged, IViewModel
    {
        public event PropertyChangedEventHandler PropertyChanged;

        private ObservableCollection<MealsGroup> _mealGroups = null;

        public ObservableCollection<MealsGroup> MealsGroups
        {
            get { return _mealGroups; }
            set
            {
                _mealGroups = value;
                OnPropertyChanged(nameof(MealsGroups));
            }
        }
        public ICommand OrderCommand { get; set; }

        public MainPageViewModel()
        {
            OrderCommand = new Command(() =>
            {
                Debug.WriteLine("MealsGroups");
            });
        }

        [NotifyPropertyChangedInvocator]
        protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
    }

和餐组

 public class MealsGroup : List<MealViewModel>
    {
        public string DisplayName { get; set; }
        public string ShortName { get; set; }

        public event MealGroupOrderSwitched MealGroupOrderSwitched;

            public ICommand OrderCommand { get; set; }

            public MealsGroup()
            {
                OrderCommand = new Command(() =>
                {
                    Debug.WriteLine("MealGroup");
                });
            }

        public void AddMeal(Meal meal)
        {
            var model = new MealViewModel
            {
                IsOrdered = meal.IsOrdered,
                MealTitle = meal.MealTitle,
                MealId = meal.MealId.Value,
                DayOfOrder = meal.DayOfOrder.Value,
                IsOrderable = meal.IsOrderable,
                IsSoup = meal.IsSoup
            };

            model.MealOrdered += meaId =>
            {
                for (var i = 0; i < Count; i++)
                {
                    var mealViewModel = this[i];
                    if (mealViewModel.MealId != meaId && mealViewModel.IsOrderable)
                        mealViewModel.IsOrdered = false;
                }
                MealGroupOrderSwitched?.Invoke(this);
            };

            Add(model);
        }
    }

但启动时Android应用程序有空列表。即使我在ctor中添加了代码中的项目。

1 个答案:

答案 0 :(得分:2)

通过将xaml ListView属性BindingContext = {binding MealsGroups}更改为ItemsSource = {binding MealsGroups}

来解决