MvvmCross get a date from a calendar UI

时间:2016-11-12 05:39:19

标签: c# calendar mvvmcross

I currently have this ViewModel called BaseballGameViewModel. What I'm trying to do is set a value in a date form for my property but I would like the date to come from a calendar UI. I'm using MvvmCross in the core therefore it would be more Android and iOS. Any help explaining anything about MvvmCross or how to go about this is appreciated. Thank you.

class BaseballGameViewModel
{
    private string _gameStartDate;
    public string GameStartDate
    {
        get { return _gameStartDate; }
        set
        {
            _gameStartDate = value;
            RaisePropertyChanged(() => GameStartDate);
        }
    }
}

1 个答案:

答案 0 :(得分:0)

我还没有使用MvvmCross的iOS日历控件,但是我可以给你一个Android实现以及ViewModel需要的样子,并且连接iOS控件应该不会太困难。

视图模型:

DateTime _gameStartDate;
public DateTime GameStartDate
{
    get { return _gameStartDate; }
    set { SetProperty(ref _gameStartDate, value); }
}

Android活动:

Button _button;
DatePickerFragment _datePicker;

protected override void OnCreate(Bundle bundle)
{
    _button = FindViewById<Button>(Resource.Id.your_button_id);
    _button.Click += Button_OnClick;
}

void Button_OnClick(object sender, EventArgs eventArgs)
{
    _datePicker = DatePickerFragment.NewInstance(delegate (DateTime date)
    {
        ViewModel.GameStartDate = date;
    });

    _datePicker.Show(FragmentManager, DatePickerFragment.TAG);
}

DatePickerFragment.cs:

public class DatePickerFragment : DialogFragment, IOnDateSetListener
{
    public static readonly string TAG = "X:" + typeof(DatePickerFragment).Name.ToUpper();

    Action<DateTime> _dateSelectedHandler = delegate { };

    public static DatePickerFragment NewInstance(Action<DateTime> onDateSelected)
    {
        var frag = new DatePickerFragment
        {
            _dateSelectedHandler = onDateSelected
        };

        return frag;
    }

    public override Dialog OnCreateDialog(Bundle savedInstanceState)
    {
        var currentDate = DateTime.Now;
        var dialog = new DatePickerDialog(Activity, this, currentDate.Year, currentDate.Month - 1, currentDate.Day);

        return dialog;
    }

    public void OnDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
    {
        var selectedDate = new DateTime(year, monthOfYear + 1, dayOfMonth);
        _dateSelectedHandler?.Invoke(selectedDate);
    }
}