Datepicker Binding Xamarin Forms

岁酱吖の 提交于 2020-01-06 07:11:59

问题


<DatePicker Date="date" Format="d MMM yyyy" HorizontalOptions="EndAndExpand" x:Name="date"/>

By having that line of code in my xaml code. how can i set the date to NOW when i create a new data?


回答1:


You can either change the Date attribute to something like this: Date="{Binding MyDate}" and then in your code-behind assign a view model to the BindingContext property. For example:

public class MyViewModel
{
    public DateTime MyDate { get; set; }
}

and in your page:

public class MyPage
{
    public MyPage()
    {
        InitializeComponent();

        var viewModel = new MyViewModel();
        viewModel = DateTime.Now;

        BindingContext = viewModel;
    }
}

Or, if you don't need to use a view model or MVVM (which I would highly recommend), you can just set it directly from your code-behind. Because you gave the DatePicker an x:Name attribute, you can refer to it by that name.

public class MyPage
{
    public MyPage()
    {
        InitializeComponent();

        date.Date = DateTime.Now;
    }
}



回答2:


You can define it in two ways

  1. Using the "x:Name" you can define the date in XAML.cs.
  2. Using the Binding property for "Date" you can define the date in ViewModel class

In your case in xaml.cs

date.Date = DateTime.Now;



来源:https://stackoverflow.com/questions/51239130/datepicker-binding-xamarin-forms

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!