简体   繁体   English

xamarin forms DatePicker 取消/确定事件

[英]xamarin forms DatePicker Cancel/OK event

I found and tried one example of a custom rendered DatePicker, for Android, for Xamarin Forms and does not show which button was clicked in UnFocus.我找到并尝试了一个自定义呈现的 DatePicker 示例,对于 Android,对于 Xamarin Forms,并且没有显示在 UnFocus 中单击了哪个按钮。 At least not for me.至少对我来说不是。 Its from stackoverflow.它来自stackoverflow。 Xamarin.Forms Android DatePicker/TimePicker button listener Xamarin.Forms Android DatePicker/TimePicker按钮监听器

Has the example in this article helped anyone else?本文中的示例对其他人有帮助吗? I really need to know when the OK button is clicked.我真的需要知道何时单击“确定”按钮。

This extends Nick Kovalsky's answer .这扩展了 Nick Kovalsky 的回答 I also fixed a bug in that answer, that meant the renderer was never used.我还修复了该答案中的一个错误,这意味着从未使用过渲染器。

Subclass DatePicker, so that you can add a new BindableProperty and a new method.子类 DatePicker,以便您可以添加新的 BindableProperty 和新方法。 Place this in your cross-platform project.把它放在你的跨平台项目中。

OKCancelDatePicker.cs: OKCancelDatePicker.cs:

using Xamarin.Forms;

// Replace with YOUR namespace.
namespace TestBugs
{
    /// <summary>
    /// NOTE: Requires custom renderer on each platform.
    /// </summary>
    public class OKCancelDatePicker : DatePicker
    {

        public static readonly BindableProperty UserCancelledProperty = BindableProperty.Create(nameof(UserCancelled), typeof(bool), typeof(OKCancelDatePicker), false);
        /// <summary>
        /// Bind to "UserCancelled", to propagate this change elsewhere (e.g. to a VM, or to trigger some logic).
        /// </summary>
        public bool UserCancelled {
            get => (bool)GetValue(UserCancelledProperty);
            set => SetValue(UserCancelledProperty, value);
        }

        /// <summary>
        /// Optionally add code here. Though usually you'll detect the change by binding to UserCancelled.
        /// </summary>
        public void OnPickerClosed()
        {
            if (UserCancelled) {
                // User cancelled.
                _ = 0;   // Dummy code, to set a breakpoint on. You can remove this.
            } else {
                // User selected OK.
                _ = 0;   // Dummy code, to set a breakpoint on. You can remove this.
            }
        }
    }
}

Create a renderer for Android.为 Android 创建渲染器。 Place this in your.Android project.把它放在你的.Android 项目中。

OKCancelDatePickerRenderer.cs: OKCancelDatePickerRenderer.cs:

using Android.App;
using Android.Content;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;
// Replace these with YOUR namespaces.
using TestBugs;   // Contains OKCancelDatePicker.
using TestBugs.Droid;   // Contains OKCancelDatePickerRenderer.

[assembly: ExportRenderer(typeof(OKCancelDatePicker), typeof(OKCancelDatePickerRenderer))]
// Replace this with YOUR Android namespace.
namespace TestBugs.Droid
{
    /// <summary>
    /// Based on Nick Kovalsky's https://stackoverflow.com/a/60786875/199364.
    /// </summary>
    public class OKCancelDatePickerRenderer : DatePickerRenderer
    {
        public OKCancelDatePickerRenderer(Context context) : base(context)
        {
        }

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.DatePicker> e)
        {
            base.OnElementChanged(e);

            //Disposing
            if (e.OldElement != null) {
                _element = null;
            }

            //Creating
            if (e.NewElement != null) {
                _element = e.NewElement as OKCancelDatePicker;
            }
        }

        protected OKCancelDatePicker _element;

        protected override DatePickerDialog CreateDatePickerDialog(int year, int month, int day)
        {
            // This mimics what the original renderer did.
            var dialog = new DatePickerDialog(Context, (o, e) =>
            {
                _element.Date = e.Date;
                ((IElementController)_element).SetValueFromRenderer(VisualElement.IsFocusedPropertyKey, false);
            }, year, month, day);

            // These use our custom actions when buttons pressed.
            dialog.SetButton((int)DialogButtonType.Positive, Context.Resources.GetString(global::Android.Resource.String.Ok), OnOk);
            dialog.SetButton((int)DialogButtonType.Negative, Context.Resources.GetString(global::Android.Resource.String.Cancel), OnCancel);

            return dialog;
        }

        private void OnCancel(object sender, DialogClickEventArgs e)
        {
            // This is what the original renderer did when Cancel pressed.
            _element.Unfocus();

            // This is our custom logic.
            _element.UserCancelled = true;
            _element?.OnPickerClosed();
        }
        private void OnOk(object sender, DialogClickEventArgs e)
        {
            // This is what the original renderer did when OK pressed.
            _element.Date = ((DatePickerDialog)sender).DatePicker.DateTime;
            _element.Unfocus();

            // This is our custom logic.
            _element.UserCancelled = false;
            _element?.OnPickerClosed();
        }
    }
}

Usage:用法:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:TestBugs"
             x:Class="TestBugs.DatePickerTestPage">
    <ContentPage.Content>
        <StackLayout>
            <Label Text="Date Picker Test Page" HorizontalOptions="CenterAndExpand" />
            <local:OKCancelDatePicker />
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

IMPORTANT: If your app runs on other platforms you'll need to do similar on each platform.重要提示:如果您的应用程序在其他平台上运行,您需要在每个平台上执行类似操作。 Per platform, try to find an example to modify.每个平台,试着找一个例子来修改。 Nick's answer has a link to one for iOS.尼克的答案有一个指向 iOS 的链接。


TBD: I should add here an example of how to bind to that UserCancelled property, so you can connect it to logic in your page.待定:我应该在这里添加一个示例,说明如何绑定到该UserCancelled属性,以便您可以将其连接到页面中的逻辑。

For now, read about Bindable Properties , and google for examples of binding to a BindableProperty of a control or view.现在,请阅读Bindable Properties和 google 以了解绑定到控件或视图的BindableProperty的示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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