簡體   English   中英

Xamarin - 在 xaml 中綁定視圖模型

[英]Xamarin - Bind view model in xaml

我正在綁定分組列表視圖以通過 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后面的代碼中添加了項目。

通過將 xaml ListView屬性BindingContext={binding MealsGroups}更改為ItemsSource={binding MealsGroups}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM