简体   繁体   中英

How to hide Cancel button in date picker in Xamarin.Forms

I have situation where the date picker should not popup with the cancel option. The reason behind is, user has to select the required date from the date picker. Here the date picker bydefault taking today's date so, Date selected event will not hit when user open datepicker and clicks Ok . If I use Unfocuss event it is hitting even when user clicks on cancel too. So, What I am thinking is to hide cancel button as there is no any direct event for Cancel or Ok for datepicker in xamarin.forms. Could someone help me with this please.

You could use CustomRenderer to achieve this effect,find the Cancel button,then set its Visibility property to Gone .like below:

[assembly: ExportRenderer(typeof(Xamarin.Forms.DatePicker), typeof(MyDatePicker))]
namespace YourNamepace.Droid
{
   class MyDatePicker:DatePickerRenderer, IOnDateSetListener
   {

      private DatePickerDialog datePickerDialog;
      private Context context;
      private DateTime currently;

      public MyDatePicker(Context context) : base(context)
      {
        this.context = context;
      }


      protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.DatePicker> e)
      {
        base.OnElementChanged(e);
        currently = DateTime.Now;
        this.Control.Click += Control_Click;

      }

      private void Control_Click(object sender, EventArgs e)
      {

        datePickerDialog = new DatePickerDialog(context,this,currently.Year,currently.Month - 1, currently.Day);
        datePickerDialog.Show();
        Android.Widget.Button cancel = datePickerDialog.GetButton((int)DialogButtonType.Negative);
        cancel.Visibility = ViewStates.Gone;
      }

      public void OnDateSet(Android.Widget.DatePicker view, int year, int month, int dayOfMonth)
      {
        DateTime selectedDate = new DateTime(year, month + 1, dayOfMonth);
        currently = selectedDate;
        Control.Text = selectedDate.ToShortDateString();
      }

 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM