如何将所选值绑定到选择器并保存此编辑页面?

时间:2019-10-06 21:17:46

标签: xamarin mvvm

我有这个Edit页面,其中有一个从Detail页面传递的ID。然后调用Web api服务以获取类别以及活动。下面的代码改编自“添加”页面。

它有2个问题:

  1. 设法获取选择器列表,然后不确定如何从选定的活动中绑定它。
  2. 在XAML中,如何将其保存为绑定名称是不同的。 Activity.Name VS Name等等等。我做错了什么?

如何解决这些问题?

以下代码:

ActivityEditPage.xaml

<?xml version="1.0" encoding="utf-8" ?>

<ContentPage.Content>
    <StackLayout  Margin="5,5,5,5" VerticalOptions="StartAndExpand">
        <Entry Placeholder="Name" Text="{Binding Activity.Name}"></Entry>
        <Picker ItemsSource="{Binding Categories}" ItemDisplayBinding="{Binding Name}"  SelectedItem="{Binding Activity.CategoryId}">
        </Picker>
        <Entry Placeholder="No of minutes" Text="{Binding Activity.NoOfMinutes}"></Entry>
        <Editor Placeholder="Description" Text="{Binding Activity.Description}"></Editor>
        <Button Text="Save" BackgroundColor="#340E22" FontSize="Small" TextColor="White" CornerRadius="30" HeightRequest="40" Command="{Binding SaveCommand}"></Button>
    </StackLayout>
</ContentPage.Content>

代码背后:

    using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace AthlosifyMobileApp.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class ActivityEditPage : ContentPage
    {
        public ActivityEditPage(int id)
        {
            InitializeComponent();
            BindingContext = new ActivityEditViewModel(Navigation, id);
        }

    }
}

ActivityEditViewModel.cs:

using AthlosifyMobileApp.Helpers;
using AthlosifyMobileApp.Models;
using AthlosifyMobileApp.Services;
using AthlosifyMobileApp.Views;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using Xamarin.Essentials;
using Xamarin.Forms;

namespace AthlosifyMobileApp.ViewModels
{
    public class ActivityEditViewModel : BaseViewModel
    {
        private readonly ApiService apiService = new ApiService();

        private int _id;
        private string _name;
        private string _description;
        private int _noOfMinutes;
        private int _categoryId;
        private string _categoryName;
        private Command _saveCommand;
        private List<Category> _categories;
        private Category _selectedCategory;
        private Activity _activity;

        public ActivityEditViewModel(INavigation navigation, int Id)
        {
            this.Navigation = navigation;
            Task.Run(async () =>
            {
                await GetCategories();
                Activity = await GetActivity(Id);
            });
        }

        public INavigation Navigation { get; set; }

        public Activity Activity
        {
            get { return _activity;  }
            set
            {
                _activity = value;
                OnPropertyChanged();
            }
        }

        public int Id
        {
            get { return _id; }
            set
            {
                _id = value;
                OnPropertyChanged();
            }
        }

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged();
                SaveCommand.ChangeCanExecute();
            }
        }

        public string Description
        {
            get { return _description; }
            set
            {
                _description = value;
                OnPropertyChanged();
            }
        }

        public int  NoOfMinutes
        {
            get { return _noOfMinutes; }
            set
            {
                _noOfMinutes = value;
                OnPropertyChanged();
            }
        }

        public int CategoryId
        {
            get { return _categoryId; }
            set
            {
                _categoryId = value;
                OnPropertyChanged();
            }
        }

        public string CategoryName
        {
            get { return _categoryName; }
            set
            {
                _categoryName = value;
                OnPropertyChanged();
            }
        }

        public List<Category> Categories
        {
            get { return _categories; }
            set
            {
                _categories = value;
                OnPropertyChanged("Categories");
            }
        }

        public Category SelectedCategory
        {
            get
            {
                return _selectedCategory;
            }
            set
            {
                _selectedCategory = value;
                OnPropertyChanged();
            }
        }

        public Command SaveCommand
        {
            get
            {
                return _saveCommand ?? (_saveCommand = new Command(ExecuteSaveCommand, CanSave));
            }
        }


        async void ExecuteSaveCommand()
        {
            var newItem = new Activity
            {
                Id = Id,
                OwnerId = Preferences.Get(Constant.Setting_UserId, ""),
                Name = Name,
                CategoryId = SelectedCategory.Id,
                CategoryName = SelectedCategory.Name,
                Description = Description,
                NoOfMinutes = NoOfMinutes
            };

            var response = await apiService.UpdateActivity(Id, newItem);
            if (!response)
            {
                await Application.Current.MainPage.DisplayAlert("Error", "Something wrong", "Alright");
            }
            else
            {
                await Navigation.PushAsync(new ActivityListPage());
            }
        }

        bool CanSave()
        {
            return !string.IsNullOrWhiteSpace(Name);
        }

        public async Task<List<Category>> GetCategories()
        {
            CategoryResult categoryResult = await apiService.GetCategories();
            return Categories = categoryResult.Results;
        }

        public async Task<Activity> GetActivity(int id)
        {
            Activity activity = await apiService.GetActivity(id);
            return activity;
        }
    }
}

更新代码

Category.cs

    public class Category
{
    public int Id { get; set; }
    public string OwnerId { get; set; }
    public int ParentId { get; set; }
    public string ParentName { get; set; }
    public string Name { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime? ModifiedDate { get; set; }
}

Activity.cs:

 public class Activity
{
    public int Id { get; set; }
    public string OwnerId { get; set; }
    public int CategoryId { get; set; }
    public string CategoryName { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public int NoOfMinutes { get; set; }
    public DateTime CreatedDate { get; set; }
    public DateTime? ModifiedDate { get; set; }
}

0 个答案:

没有答案