Xamarin C# - Android - Prevent an AlertDialog from closing on PositiveButton click

后端 未结 1 855
灰色年华
灰色年华 2021-02-05 15:47

I\'m new to Xamarin and I don\'t know how to do the following in c#. I want to prevent an alertdialog from closing when clicking on the Positive/Negative buttons. I need to do s

相关标签:
1条回答
  • 2021-02-05 16:37

    This requires to think a bit outside the box. You will have to manipulate the AlertDialog object directly:

    // Build the dialog.
    var builder = new AlertDialog.Builder(this);
    builder.SetTitle("Click me!");
    
    // Create empty event handlers, we will override them manually instead of letting the builder handling the clicks.
    builder.SetPositiveButton("Yes", (EventHandler<DialogClickEventArgs>)null);
    builder.SetNegativeButton("No", (EventHandler<DialogClickEventArgs>)null);
    var dialog = builder.Create();
    
    // Show the dialog. This is important to do before accessing the buttons.
    dialog.Show();
    
    // Get the buttons.
    var yesBtn = dialog.GetButton((int)DialogButtonType.Positive);
    var noBtn = dialog.GetButton((int)DialogButtonType.Negative);
    
    // Assign our handlers.
    yesBtn.Click += (sender, args) =>
    {
        // Don't dismiss dialog.
        Console.WriteLine("I am here to stay!");
    };
    noBtn.Click += (sender, args) =>
    {
        // Dismiss dialog.
        Console.WriteLine("I will dismiss now!");
        dialog.Dismiss();
    };
    
    0 讨论(0)
提交回复
热议问题