這是我的代碼,我想當月份值改變時,我的日期選擇器值會改變。日值取決于月份。例如,如果月份值為 1、3、5、7、8、10、12,則日值為 31,否則日值為 30。如果月份為 2 月,則日值為 28,并且取決于閏年。
我將 XAMARIN 與 C# 一起使用。
謝謝!
public class DayMonthYearPickerDialog : Android.Support.V4.App.DialogFragment
{
public event EventHandler<DateTime> OnDateTimeChanged;
public event EventHandler<DateTime> OnClosed;
public DateTime? Date { get; set; }
public void Hide() => base.Dialog?.Hide();
public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
AlertDialog.Builder builder = new AlertDialog.Builder(Activity);
// Get the layout inflater
LayoutInflater inflater = Activity.LayoutInflater;
var selectedDate = GetSelectedDate();
Calendar cal = Calendar.Instance;
View dialog = inflater.Inflate(Resource.Layout.date_picker_dialog, null);
NumberPicker monthPicker = (NumberPicker)dialog.FindViewById(Resource.Id.picker_month);
NumberPicker yearPicker = (NumberPicker)dialog.FindViewById(Resource.Id.picker_year);
NumberPicker dayPicker = (NumberPicker)dialog.FindViewById(Resource.Id.picker_day);
monthPicker.MinValue = 1;
monthPicker.MaxValue = 12;
monthPicker.Value = cal.Get(CalendarField.Month) 1;
dayPicker.MinValue = 1;
dayPicker.MaxValue = 31;
dayPicker.Value = cal.Get(CalendarField.DayOfMonth);
int year = cal.Get(CalendarField.Year);
yearPicker.MinValue = 1900;
yearPicker.MaxValue = year;
yearPicker.Value = year;
builder.SetView(dialog)
.SetPositiveButton("Ok", (sender, e) =>
{
selectedDate = new DateTime(yearPicker.Value, monthPicker.Value, dayPicker.Value);
OnDateTimeChanged?.Invoke(dialog, selectedDate);
})
.SetNegativeButton("Cancel", (sender, e) =>
{
Dialog.Cancel();
OnClosed?.Invoke(dialog, selectedDate);
}); return builder.Create();
uj5u.com熱心網友回復:
您可以將 ValueChanged 事件添加到 monthPicker。如:
var month = new List<int>() {1,3,5,7,8,10,12 };
monthPicker.ValueChanged = (s, e) =>
{
if(month.Contains(monthPicker.Value))
{
dayPicker.MaxValue = 31;
}else if(monthPicker.Value == 2 && yearPicker.Value %4 == 0)
{
dayPicker.MaxValue = 28;
}else if(monthPicker.Value == 2 && yearPicker.Value % 4 != 0)
{
dayPicker.MaxValue = 29;
}
else
{
dayPicker.MaxValue = 30;
}
};
更新
我的意思是你可以用DateTime.Now. 然后設定日期選擇器的最大值。如:
yearPicker.Value = DateTime.Now.Year;
monthPicker.Value = DateTime.Now.Month;
dayPicker.MaxValue = DateTime.DaysInMonth(DateTime.Now.Year,DateTime.Now.Month);
dayPicker.Value = DateTime.Now.Day;// Set value must after set the min and max, or the default value will be 0
所以似乎我們不需要使用if() else. 我們可以只使用以下代碼:
monthPicker.ValueChanged = (s, e) =>
{
dayPicker.MaxValue = DateTime.DaysInMonth(yearPicker.Value,monthPicker.Value);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/480225.html
標籤:C# 视觉工作室 xamarin xamarin.android
