我有两个DatePicker(名为fromdate和todate)和一个按钮(名为save).
默认情况下,今天的日期将在DatePicker中填充.我已经添加了最小日期验证(用户只能选择今天或更长的日期.
如果今天的日期是5月30日,并且用户从outdate选择6月15日并单击确定.现在,默认的今天日期显示在todate中.
我希望验证,如果用户在fromdate中选择6月15日并单击“确定”,则应使用fromdate填充todate.
解决方法:
这可以通过将toDate DatePicker的MinimumDate绑定到FromDate属性来完成.
我不知道你的代码所以我会给你一个例子:
想象一下,你有一个像这样的XAML:
<?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:local="clr-YourProject"
x:Class="YourProject.YourClass">
<StackLayout>
<DatePicker Date="{Binding FromDate}" MinimumDate="{Binding FromMiminumDate}" />
<DatePicker Date="{Binding ToDate}" MinimumDate="{Binding FromDate}" />
</StackLayout>
</ContentPage>
你有一个像这样的ViewModel:
public class YourViewModel : INotifyPropertyChanged
{
public YourViewModel ()
{
FromMiminumDate = DateTime.Today;
}
private DateTime _fromDate;
public DateTime FromDate
{
get { return _fromDate; }
set
{
if (_fromDate == value)
return;
_fromDate = value;
NotifyPropertyChanged (nameof(FromDate));
}
}
private DateTime _toDate;
public DateTime ToDate
{
get { return _toDate; }
set
{
if (_toDate == value)
return;
_toDate = value;
NotifyPropertyChanged (nameof(ToDate));
}
}
private DateTime _fromMiminumDate;
public DateTime FromMiminumDate
{
get { return _fromMiminumDate; }
set
{
if (_fromMiminumDate == value)
return;
_fromMiminumDate = value;
NotifyPropertyChanged (nameof(FromMiminumDate));
}
}
public event PropertyChangedEventHandler PropertyChanged;
void NotifyPropertyChanged (string propertyName)
{
PropertyChanged?.Invoke (this, new PropertyChangedEventArgs (propertyName));
}
}
这将使每次更改FromDate Picker中选择的日期时,ToDate Picker的MinimumDate也将更改.
当然,后面的XAML代码将如下所示:
public YourClass ()
{
var VM = new YourViewModel ();
InitializeComponent ();
BindingContext = VM;
}
希望这可以帮助.