简体   繁体   English

Xamarin - 在 xaml 中绑定视图模型

[英]Xamarin - Bind view model in xaml

I'm binding grouped listview to view model data source via xaml.我正在绑定分组列表视图以通过 xaml 查看模型数据源。 But when the app is launched the list is empty even when I populate it from code behind in ctor.但是当应用程序启动时,即使我从 ctor 中的代码填充它,列表也是空的。 When I declare the ListView x:Name="myList" and populate it from code behind it works, but it's not "binded" to the view model directly.当我声明 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>

Code behind:后面的代码:

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;
        }

This is View Model:这是视图模型:

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));
        }
    }

And meal group和饭团

 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);
        }
    }

but the android app when launched has empty list.但是启动时的 android 应用程序有空列表。 Even when I added items in code behind in ctor.即使我在ctor后面的代码中添加了项目。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 将自定义视图绑定到xamarin形式的页面模型 - Bind a custom view to page model in xamarin forms Xamarin UWP 似乎绑定到错误的视图 model - Xamarin UWP seems to bind to the wrong view model 如何在Xamarin中从视图到视图模型绑定数据? - How to data bind from view to view model in Xamarin? 如何将视图的 BackgroundColor 属性绑定到 Xamarin Forms 中的视图模型? - How to bind the BackgroundColor property of a view to a View Model in Xamarin Forms? 在带有棱镜mvvm视图模型的xamarin形式的xaml中包括xaml。 无法解析INavigationService - include xaml in xaml on xamarin forms with prism mvvm view model. Cannot resolve INavigationService 如何将SwitchCell文本颜色绑定到Xamarin.Forms中的视图模型 - How to bind SwitchCell text color to view model in Xamarin.Forms MVVM Xamarin Forms - 绑定视图模型属性的命令参数 - MVVM Xamarin Forms - Command Pararameter to Bind View Model property Xamarin形式的EmbeddedImage:如何在XAML中绑定它 - EmbeddedImage in Xamarin Forms: how to bind it in XAML Xamarin,XAML。 帮助在 ListView 中绑定颜色 - Xamarin, XAML. Help bind color in ListView 当页面绑定上下文设置为 Xamarin 中的不同视图 model 时,如何将控件绑定到视图 model - How to bind a control to a view model when page binding context is set to a different view model in Xamarin
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM