问题
<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
- Using the "x:Name" you can define the date in XAML.cs.
- 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