コード例 #1
0
        public override void SelectionDidChange(NSNotification notification)
        {
            Console.WriteLine(notification);
            var table = notification.Object as NSTableView;
            var row   = table.SelectedRow;

            // Anything to process
            if (row < 0)
            {
                return;
            }

            // Get current values from the data source
            var name = (NSString)table.DataSource.GetObjectValue(table, new NSTableColumn("name"), row);
            var id   = (NSString)table.DataSource.GetObjectValue(table, new NSTableColumn("id"), row);

            // Confirm deletion of a todo item
            var alert = new NSAlert {
                AlertStyle      = NSAlertStyle.Critical,
                InformativeText = string.Format("Do you want to delete row {0}?", name),
                MessageText     = "Delete Todo",
            };

            alert.AddButton("Cancel");
            alert.AddButton("Delete");
            alert.BeginSheetForResponse(windowController.Window, async result => {
                Console.WriteLine("Alert Result: {0}", result);
                if (result == 1001)
                {
                    await windowController.Delete(id);
                }
                table.DeselectAll(this);
            });
        }
コード例 #2
0
		public void DeletePerson(NSWindow window) {
			if (View.SelectedRow == -1) {
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Critical,
					InformativeText = "Please select the person to remove from the list of people.",
					MessageText = "Delete Person",
				};
				alert.BeginSheet (window);
			} else {
				// Grab person
				SelectedPerson = _people.GetItem<PersonModel> ((nuint)View.SelectedRow);

				// Confirm delete
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Critical,
					InformativeText = string.Format("Are you sure you want to delete person `{0}` from the table?",SelectedPerson.Name),
					MessageText = "Delete Person",
				};
				alert.AddButton ("Ok");
				alert.AddButton ("Cancel");
				alert.BeginSheetForResponse (window, (result) => {
					// Delete?
					if (result == 1000) {
						RemovePerson(View.SelectedRow);
					}
				});
			}
		}
コード例 #3
0
        private void DeleteOnClick(object sender, EventArgs e)
        {
            // Get button and product
            var btn     = sender as NSButton;
            var balance = DataSource.Balances[(int)btn.Tag];

            // Configure alert
            var alert = new NSAlert()
            {
                AlertStyle      = NSAlertStyle.Informational,
                InformativeText = $"你真的要删掉我吗?>.<",
                MessageText     = $"Delete?",
            };

            alert.AddButton("取消");
            alert.AddButton("删除");
            alert.BeginSheetForResponse(Controller.View.Window, (result) =>
            {
                // Should we delete the requested row?
                if (result == 1001)
                {
                    // Remove the given row from the dataset

                    var conn = new SQLite.SQLiteConnection(Controller.GetDbPath());
                    conn.Delete(DataSource.Balances[(int)btn.Tag]);

                    Controller.ReloadTable();
                }
            });
        }
コード例 #4
0
        public void LidmaatschapRemoveClicked(Foundation.NSObject sender)
        {
            Debug.WriteLine("Start: PersoonController.LidmaatschapRemoveClicked");

            var selectedRowIndex = (int)LidmaatschappenTable.SelectedRow;

            if (selectedRowIndex >= 0)
            {
                SelectedLidmaatschap = dsLidmaatschappen.Lidmaatschappen[selectedRowIndex] as ClublidmaatschapModel;

                // Configure alert
                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Informational,
                    InformativeText = $"Weet je zeker dat je het lidmaatschap op {SelectedLidmaatschap.ClubNaam} wilt verwijderen?\n\nDit kan niet meer ongedaan gemaakt worden.",
                    MessageText     = $"Delete {SelectedLidmaatschap.ClubNaam}?",
                };
                alert.AddButton("Cancel");
                alert.AddButton("Delete");
                alert.BeginSheetForResponse(this.View.Window, (result) =>
                {
                    // Should we delete the requested row?
                    if (result == 1001)
                    {
                        // Remove the given row from the dataset
                        SelectedLidmaatschap.Delete(AppDelegate.Conn);
                        dsLidmaatschappen.Lidmaatschappen.Remove(SelectedLidmaatschap);

                        LidmaatschappenTable.ReloadData();
                    }
                });
            }

            Debug.WriteLine("Einde: PersoonController.LidmaatschapRemoveClicked");
        }
コード例 #5
0
ファイル: MainWindow.cs プロジェクト: brianmed/DiskReport
        partial void ClickedTrash(Foundation.NSObject sender)
        {
            if (0 == FileResults.SelectedRows.Count)
            {
                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Warning,
                    InformativeText = "Please select a path",
                    MessageText     = "Action Info",
                };

                alert.BeginSheet(this);

                return;
            }

            var ask = new NSAlert()
            {
                MessageText = "Are you sure?"
            };

            ask.AddButton("Move to Trash");
            ask.AddButton("Cancel");

            ask.BeginSheetForResponse(this, (result) => {
                if (1000 != result)
                {
                    return;
                }

                DelAction();
            });
        }
コード例 #6
0
        public void DeletePerson(NSWindow window)
        {
            if (View.SelectedRow == -1)
            {
                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Critical,
                    InformativeText = "Please select the person to remove from the list of people.",
                    MessageText     = "Delete Person",
                };
                alert.BeginSheet(window);
            }
            else
            {
                // Grab person
                SelectedPerson = _people.GetItem <PersonModel> ((nuint)View.SelectedRow);

                // Confirm delete
                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Critical,
                    InformativeText = string.Format("Are you sure you want to delete person `{0}` from the table?", SelectedPerson.Name),
                    MessageText     = "Delete Person",
                };
                alert.AddButton("Ok");
                alert.AddButton("Cancel");
                alert.BeginSheetForResponse(window, (result) => {
                    // Delete?
                    if (result == 1000)
                    {
                        RemovePerson(View.SelectedRow);
                    }
                });
            }
        }
コード例 #7
0
ファイル: TableDelegate.cs プロジェクト: runecats/mac-samples
		public override void SelectionDidChange (NSNotification notification)
		{
			Console.WriteLine (notification);
			var table = notification.Object as NSTableView;
			var row = table.SelectedRow;

			// Anything to process
			if (row < 0)
				return;

			// Get current values from the data source
			var name = table.DataSource.GetObjectValue (table, new NSTableColumn("name"), row) + "";
			var id = table.DataSource.GetObjectValue (table, new NSTableColumn("id"), row) + "";

			// Confirm deletion of a todo item
			var alert = new NSAlert () {
				AlertStyle = NSAlertStyle.Critical,
				InformativeText = "Do you want to delete row " + name + "?",
				MessageText = "Delete Todo",
			};
			alert.AddButton ("Cancel");
			alert.AddButton ("Delete");
			alert.BeginSheetForResponse (windowController.Window, async (result) => {
				Console.WriteLine ("Alert Result: {0}", result);
				if (result == 1001) {
					await windowController.Delete(id);
				}
				table.DeselectAll(this);
			});
		}
コード例 #8
0
        partial void ClubRemoveClicked(NSButton sender)
        {
            Debug.WriteLine("Start: ClubsController.ClubRemoveClicked");

            if ((int)ClubsTable.SelectedRow >= 0)
            {
                SelectedClub = ds.Clubs[(int)ClubsTable.SelectedRow] as ClubModel;

                // Configure alert
                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Informational,
                    InformativeText = $"Weet je zeker dat je de club {SelectedClub.ClubNaam} wilt verwijderen?\n\nDit kan niet meer ongedaan gemaakt worden.",
                    MessageText     = $"Delete {SelectedClub.ClubNaam}?",
                };
                alert.AddButton("Cancel");
                alert.AddButton("Delete");
                alert.BeginSheetForResponse(this.View.Window, (result) =>
                {
                    // Should we delete the requested row?
                    if (result == 1001)
                    {
                        // Remove the given row from the dataset
                        SelectedClub.Delete(AppDelegate.Conn);
                        ds.Clubs.Remove(SelectedClub);
                        ReloadTable();
                    }
                });
            }

            Debug.WriteLine("Einde: ClubsController.ClubRemoveClicked");
        }
コード例 #9
0
        partial void PersoonRemoveClicked(Foundation.NSObject sender)
        {
            Debug.WriteLine("Start: PersonenController.PersoonRemoveClicked");

            if ((int)PersonenTable.SelectedRow >= 0)
            {
                var selectedRowIndex = PersonenTable.SelectedRow;
                SelectedPersoon = dsPersonen.Personen[(int)PersonenTable.SelectedRow] as PersoonModel;

                // Configure alert
                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Informational,
                    InformativeText = $"Weet je zeker dat je de persoon {SelectedPersoon.Achternaam} wilt verwijderen?\n\nDit kan niet meer ongedaan gemaakt worden.",
                    MessageText     = $"Delete {SelectedPersoon.Achternaam}?",
                };
                alert.AddButton("Cancel");
                alert.AddButton("Delete");
                alert.BeginSheetForResponse(this.View.Window, (result) =>
                {
                    // Should we delete the requested row?
                    if (result == 1001)
                    {
                        // Remove the given row from the dataset
                        SelectedPersoon.Delete(AppDelegate.Conn);
                        dsPersonen.Personen.Remove(SelectedPersoon);
                        ReloadTable();
                    }
                });
            }
            Debug.WriteLine("Einde: PersonenController.PersoonRemoveClicked");
        }
コード例 #10
0
 public void DeleteCheat(NSWindow window)
 {
     if (CheatTableView.SelectedRow == -1)
     {
         var alert = new NSAlert
         {
             AlertStyle      = NSAlertStyle.Critical,
             InformativeText = NSBundle.MainBundle.LocalizedString("Please select the cheat to remove from the list of cheats.", null),
             MessageText     = NSBundle.MainBundle.LocalizedString("Delete Cheat", null),
         };
         alert.BeginSheet(window);
     }
     else
     {
         SelectedCheat = _cheats.GetItem <CheatModel>((nuint)CheatTableView.SelectedRow);
         var message = NSBundle.MainBundle.LocalizedString("Are you sure you want to delete cheat `{0:X}` from the table?", null);
         // Confirm delete
         var alert = new NSAlert
         {
             AlertStyle      = NSAlertStyle.Critical,
             InformativeText = string.Format(message, SelectedCheat.Address),
             MessageText     = NSBundle.MainBundle.LocalizedString("Delete Cheat", null),
         };
         alert.AddButton(NSBundle.MainBundle.LocalizedString("OK", null));
         alert.AddButton(NSBundle.MainBundle.LocalizedString("Cancel", null));
         alert.BeginSheetForResponse(window, (result) =>
         {
             // Delete?
             if (result == 1000)
             {
                 RemoveCheat(CheatTableView.SelectedRow);
             }
         });
     }
 }
コード例 #11
0
 public void DeletePerson(NSWindow window)
 {
     // Anything to process?
     if (SelectedPerson == null)
     {
         var alert = new NSAlert()
         {
             AlertStyle      = NSAlertStyle.Critical,
             InformativeText = "Please select the person to remove from the collection of people.",
             MessageText     = "Delete Person",
         };
         alert.BeginSheet(window);
     }
     else
     {
         // Confirm delete
         var alert = new NSAlert()
         {
             AlertStyle      = NSAlertStyle.Critical,
             InformativeText = string.Format("Are you sure you want to delete person `{0}` from the collection?", SelectedPerson.Name),
             MessageText     = "Delete Person",
         };
         alert.AddButton("Ok");
         alert.AddButton("Cancel");
         alert.BeginSheetForResponse(window, (result) => {
             // Delete?
             if (result == 1000)
             {
                 RemovePerson(View.SelectionIndex);
             }
         });
     }
 }
コード例 #12
0
		public void DeletePerson(NSWindow window) {

			// Anything to process?
			if (SelectedPerson == null) {
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Critical,
					InformativeText = "Please select the person to remove from the collection of people.",
					MessageText = "Delete Person",
				};
				alert.BeginSheet (window);
			} else {
				// Confirm delete
				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Critical,
					InformativeText = string.Format ("Are you sure you want to delete person `{0}` from the collection?", SelectedPerson.Name),
					MessageText = "Delete Person",
				};
				alert.AddButton ("Ok");
				alert.AddButton ("Cancel");
				alert.BeginSheetForResponse (window, (result) => {
					// Delete?
					if (result == 1000) {
						RemovePerson (View.SelectionIndex);
					}
				});
			}
		}
コード例 #13
0
        public override IDisposable Login(LoginConfig config) => this.Present(() =>
        {
            var alert = new NSAlert
            {
                AlertStyle      = NSAlertStyle.Informational,
                MessageText     = config.Title ?? string.Empty,
                InformativeText = config.Message ?? string.Empty
            };
            alert.AddButton(config.OkText);
            alert.AddButton(config.CancelText);

            var inputView = new NSStackView(new CGRect(0, 2, 200, 58));
            var txtUser   = new NSTextField(new CGRect(0, 28, 200, 24))
            {
                PlaceholderString = config.LoginPlaceholder,
                StringValue       = config.LoginValue ?? string.Empty
            };
            var txtPassword = new NSSecureTextField(new CGRect(0, 2, 200, 24))
            {
                PlaceholderString = config.PasswordPlaceholder
            };

            inputView.AddSubview(txtUser);
            inputView.AddSubview(txtPassword);

            alert.AccessoryView = inputView;
            alert.Layout();

            alert.BeginSheetForResponse(this.windowFunc(), result => config.OnAction?.Invoke(new LoginResult(result == 1000, txtUser.StringValue, txtPassword.StringValue)));
            return(alert);
        });
コード例 #14
0
        public override IDisposable Prompt(PromptConfig config) => this.Present(() =>
        {
            var alert = new NSAlert
            {
                AlertStyle      = NSAlertStyle.Informational,
                MessageText     = config.Title ?? string.Empty,
                InformativeText = config.Message ?? string.Empty
            };
            alert.AddButton(config.OkText);
            if (config.IsCancellable)
            {
                alert.AddButton(config.CancelText);
            }

            var txtInput = new NSTextField(new CGRect(0, 0, 300, 24))
            {
                PlaceholderString = config.Placeholder ?? string.Empty,
                StringValue       = config.Text ?? String.Empty
            };

            // TODO: Implement input types validation
            if (config.InputType != InputType.Default || config.MaxLength != null)
            {
                Log.Warn("Acr.UserDialogs", "There is no validation of input types nor MaxLength on this implementation");
            }

            alert.AccessoryView = txtInput;
            alert.Layout();

            alert.BeginSheetForResponse(this.windowFunc(), result => config.OnAction?.Invoke(new PromptResult(result == 1000, txtInput.StringValue)));
            return(alert);
        });
コード例 #15
0
        void __ViewModel_OnError(string errorText, string errorDescription = "")
        {
            var alert = new NSAlert();

            alert.MessageText     = errorText;
            alert.InformativeText = errorDescription;

            alert.AddButton(LocalizedStrings.Instance.LocalizedString("Button_Close"));
            alert.BeginSheetForResponse(View.Window, (result) => { });
        }
コード例 #16
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            ActivityLog.DataSource = log;
            ActivityLog.Delegate   = new ActivityLogDelegate(log);

            // Fire the timer once a second
            MainTimer          = new Timer(1000);
            MainTimer.Elapsed += (sender, e) => {
                TimeLeft--;
                // Format the remaining time nicely for the label
                TimeSpan time       = TimeSpan.FromSeconds(TimeLeft);
                string   timeString = time.ToString(@"mm\:ss");
                InvokeOnMainThread(() => {
                    // We want to interact with the UI from a different thread,
                    // so we must invoke this change on the main thread
                    TimerLabel.StringValue = timeString;
                });

                // If 25 minutes have passed
                if (TimeLeft == 0)
                {
                    // Stop the timer and reset
                    MainTimer.Stop();
                    TimeLeft = 1500;

                    InvokeOnMainThread(() => {
                        // Reset the UI
                        TimerLabel.StringValue = "25:00";
                        StartStopButton.Title  = "Start";

                        NSAlert alert = new NSAlert();
                        // Set the style and message text
                        alert.AlertStyle  = NSAlertStyle.Informational;
                        alert.MessageText = "25 Minutes elapsed! Take a 5 minute break and fill out your completed task.";
                        // The text field we are going to add to the sheet
                        var input = new NSTextField(new CGRect(0, 0, 300, 20));
                        // Add the text field to the sheet
                        alert.AccessoryView = input;

                        // Get the current time
                        DateTime CurrentTime = DateTime.Now;
                        // Display the NSAlert from the current view
                        alert.BeginSheetForResponse(View.Window, (result) =>
                        {
                            // When the sheet is dismissed add the activity to the log
                            log.Activities.Add(new Activity(CurrentTime, input.StringValue));
                            ActivityLog.ReloadData();
                        });
                    });
                }
            };
        }
コード例 #17
0
 public override IDisposable Alert(AlertConfig config) => this.Present(() =>
 {
     var alert = new NSAlert
     {
         AlertStyle      = NSAlertStyle.Informational,
         MessageText     = config.Title ?? string.Empty,
         InformativeText = config.Message
     };
     alert.AddButton(config.OkText);
     alert.BeginSheetForResponse(this.windowFunc(), _ => config.OnAction?.Invoke());
     return(alert);
 });
コード例 #18
0
        partial void AlertAddsAlertButton(NSObject sender)
        {
            var alert = new NSAlert()
            {
                AlertStyle      = NSAlertStyle.Informational,
                InformativeText = "This is the body of the alert where you describe the situation and any actions to correct it.",
                MessageText     = "Alert Title"
            };

            alert.AddButton("OK");
            alert.AddButton("Cancel");
            alert.AddButton("Maybe");
            alert.BeginSheetForResponse(this.View.Window, (result) => {
                Console.WriteLine("Alert Result:{0}", result);
            });
        }
コード例 #19
0
        //Update initial
        partial void UpdateInitAmt(NSButton updateInitBtn)
        {
            ////Push data
            var conn           = new SQLite.SQLiteConnection(DbPath);
            var initial        = conn.Table <InitialValue>().OrderByDescending(x => x.id).First();
            var initialValue   = initial.Value;
            var initialValueId = initial.id;

            // Wireup events
            updateInitBtn.Activated += (sender, e) => {
                // Get button and product
                var btn = sender as NSButton;

                // Configure alert
                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Informational,
                    InformativeText = $"可以修改你的初始Money",
                    MessageText     = $"修改初始",
                };
                alert.AddButton("取消");
                alert.AddButton("确定");

                // initial value override
                var input = new NSTextField(new CGRect(0, 0, 300, 20));
                input.StringValue   = String.Format("{0}", initialValue);
                alert.AccessoryView = input;
                alert.Layout();

                alert.BeginSheetForResponse(View.Window, (result) =>
                {
                    Console.WriteLine(result);
                    // Should we delete the requested row?
                    if (result == 1001)
                    {
                        // update init value

                        conn.Update(new InitialValue(float.Parse(input.StringValue)));
                        Console.WriteLine(conn.Update(new InitialValue(float.Parse(input.StringValue), initialValueId)));
                        Console.WriteLine(conn.Table <InitialValue>().OrderByDescending(x => x.id).First().Value);
                        ReloadTable();
                    }
                });
            };
        }
コード例 #20
0
        public static void CreateAlert(this NSViewController view, string title, string message, Action action, NSAlertStyle style = NSAlertStyle.Informational)
        {
            view.InvokeOnMainThread(() => {
                var alert = new NSAlert
                {
                    InformativeText = message ?? "",
                    AlertStyle      = style,
                    MessageText     = title
                };

                alert.BeginSheetForResponse(view.View.Window, (result) => {
                    if (action != null)
                    {
                        action();
                    }
                });
            });
        }
コード例 #21
0
        private void OnRunJavaScriptTextInputPanel(WKWebView webview, string prompt, string defaultText, WKFrameInfo frame, Action <string> completionHandler)
        {
            if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
            {
                this.Log().Debug($"OnRunJavaScriptTextInputPanel: {prompt}, {defaultText}");
            }

#if __IOS__
            var         alert          = UIKit.UIAlertController.Create(string.Empty, prompt, UIKit.UIAlertControllerStyle.Alert);
            UITextField alertTextField = null;

            alert.AddTextField((textField) =>
            {
                textField.Placeholder = defaultText;
                alertTextField        = textField;
            });

            alert.AddAction(UIKit.UIAlertAction.Create(OkString, UIKit.UIAlertActionStyle.Default,
                                                       okAction => completionHandler(alertTextField.Text)));

            alert.AddAction(UIKit.UIAlertAction.Create(CancelString, UIKit.UIAlertActionStyle.Cancel,
                                                       cancelAction => completionHandler(null)));

            var controller = webview.FindViewController();
            controller?.PresentViewController(alert, true, null);
#else
            var alert = new NSAlert()
            {
                AlertStyle      = NSAlertStyle.Informational,
                InformativeText = prompt,
            };
            var textField = new NSTextField(new CGRect(0, 0, 300, 20))
            {
                PlaceholderString = defaultText,
            };
            alert.AccessoryView = textField;
            alert.AddButton(OkString);
            alert.AddButton(CancelString);
            alert.BeginSheetForResponse(webview.Window, (result) => {
                var okButtonClicked = result == 1000;
                completionHandler(okButtonClicked ? textField.StringValue : null);
            });
#endif
        }
コード例 #22
0
ファイル: ViewController.cs プロジェクト: RALEx147/NEOSx
        partial void exit(NSObject sender)
        {
            var alert = new NSAlert()
            {
                AlertStyle      = NSAlertStyle.Warning,
                InformativeText = $"Are you sure you want to exit? Blockchain syncing will stop.",
            };

            alert.AddButton("Cancel");
            alert.AddButton("Exit");

            alert.BeginSheetForResponse(base.View.Window, (result) =>
            {
                if (result == 1001)
                {
                    NSApplication.SharedApplication.Terminate(sender);
                }
            });
        }
コード例 #23
0
        void ShowAlert(NSObject sender)
        {
            if (ShowAlertAsSheet)
            {
                var input = new NSTextField(new CGRect(0, 0, 300, 20));

                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Informational,
                    InformativeText = "This is the body of the alert where you describe the situation and any actions to correct it.",
                    MessageText     = "Alert Title",
                };
                alert.AddButton("Ok");
                alert.AddButton("Cancel");
                alert.AddButton("Maybe");
                alert.ShowsSuppressionButton = true;
                alert.AccessoryView          = input;
                alert.Layout();
                alert.BeginSheetForResponse(this, (result) => {
                    Console.WriteLine("Alert Result: {0}, Suppress: {1}", result, alert.SuppressionButton.State == NSCellStateValue.On);
                });
            }
            else
            {
                var input = new NSTextField(new CGRect(0, 0, 300, 20));

                var alert = new NSAlert()
                {
                    AlertStyle      = NSAlertStyle.Informational,
                    InformativeText = "This is the body of the alert where you describe the situation and any actions to correct it.",
                    MessageText     = "Alert Title",
                };
                alert.AddButton("Ok");
                alert.AddButton("Cancel");
                alert.AddButton("Maybe");
                alert.ShowsSuppressionButton = true;
                alert.AccessoryView          = input;
                alert.Layout();
                var result = alert.RunModal();
                Console.WriteLine("Alert Result: {0}, Suppress: {1}", result, alert.SuppressionButton.State == NSCellStateValue.On);
            }
        }
コード例 #24
0
        void Run(NSAlert alert)
        {
            switch (AlertOptions.SelectedTag)
            {
            case 0:
                alert.BeginSheetForResponse(Window, response => ShowResponse(alert, response));
                break;

            case 1:
                ShowResponse(alert, alert.RunSheetModal(Window));
                break;

            case 2:
                ShowResponse(alert, alert.RunModal());
                break;

            default:
                ResultLabel.StringValue = "Unknown Alert Option";
                break;
            }
        }
コード例 #25
0
        partial void removeEmployee(Foundation.NSObject sender)
        {
            // Which row(s) are selected?
            NSIndexSet rows = tableView.SelectedRows;

            // Is the selection empty?
            if (rows.Count == 0)
            {
                AppKitFramework.NSBeep();
                return;
            }
            NSAlert alert = NSAlert.WithMessage(NSBundle.MainBundle.LocalizedString("REMOVE_MSG", null),
                                                NSBundle.MainBundle.LocalizedString("CANCEL", null),
                                                NSBundle.MainBundle.LocalizedString("OK", null),
                                                NSBundle.MainBundle.LocalizedString("NO_RAISE", null),
                                                "");

            alert.InformativeText = String.Format("{0} {1} {2}",
                                                  rows.Count,
                                                  rows.Count == 1 ? NSBundle.MainBundle.LocalizedString("EMPLOYEE", null) : NSBundle.MainBundle.LocalizedString("EMPLOYEES", null),
                                                  NSBundle.MainBundle.LocalizedString("REMOVE_INF", null));
            alert.BeginSheetForResponse(tableView.Window, (response) => GetResponse(alert, response));
        }
コード例 #26
0
        private void OnRunJavaScriptConfirmPanel(WKWebView webview, string message, WKFrameInfo frame, Action <bool> completionHandler)
        {
            if (this.Log().IsEnabled(Microsoft.Extensions.Logging.LogLevel.Debug))
            {
                this.Log().DebugFormat("OnRunJavaScriptConfirmPanel: {0}", message);
            }

            /*
             *	Code taken from:
             *  https://github.com/xamarin/recipes/pull/20/files
             */
            var controller = webview.FindViewController();

#if __IOS__
            var alert = UIKit.UIAlertController.Create(string.Empty, message, UIKit.UIAlertControllerStyle.Alert);
            alert.AddAction(UIKit.UIAlertAction.Create(OkString, UIKit.UIAlertActionStyle.Default,
                                                       okAction => completionHandler(true)));

            alert.AddAction(UIKit.UIAlertAction.Create(CancelString, UIKit.UIAlertActionStyle.Cancel,
                                                       cancelAction => completionHandler(false)));

            controller?.PresentViewController(alert, true, null);
#else
            var alert = new NSAlert()
            {
                AlertStyle      = NSAlertStyle.Informational,
                InformativeText = message,
            };
            alert.AddButton(OkString);
            alert.AddButton(CancelString);
            alert.BeginSheetForResponse(webview.Window, (result) => {
                var okButtonClicked = result == 1000;
                completionHandler(okButtonClicked);
            });
#endif
        }
コード例 #27
0
        protected virtual NSAlert CreateNativeActionSheet(ActionSheetConfig config)
        {
            var alert = new NSAlert
            {
                AlertStyle      = NSAlertStyle.Informational,
                MessageText     = config.Title ?? string.Empty,
                InformativeText = config.Message ?? string.Empty
            };

            if (config.Cancel != null)
            {
                alert.AddButton(config.Cancel.Text);
            }

            var extraSpace = config.Destructive == null ? 30 : 60;
            var inputView  = new NSStackView(new CGRect(0, 0, 200, (config.Options.Count * 30) + extraSpace));

            var yPos = config.Options.Count * 30 + (config.Destructive == null ? 0 : 1) * 30;

            foreach (var item in config.Options)
            {
                this.AddActionSheetOption(item, alert.Window, inputView, yPos);
                yPos -= 30;
            }

            if (config.Destructive != null)
            {
                this.AddActionSheetOption(config.Destructive, alert.Window, inputView, yPos, true);
            }

            alert.AccessoryView = inputView;
            alert.Layout();

            alert.BeginSheetForResponse(this.windowFunc(), _ => { });
            return(alert);
        }
コード例 #28
0
        /// <summary>
        /// Deletes the person currently selected from the collection view.
        /// </summary>
        public void DeletePerson()
        {
            // Confirm removal
            var alert = new NSAlert()
            {
                AlertStyle      = NSAlertStyle.Informational,
                InformativeText = $"Are you sure you want to delete {PersonSelected.Name}?.",
                MessageText     = "Delete Employee",
            };

            alert.AddButton("Ok");
            alert.AddButton("Cancel");
            alert.BeginSheetForResponse(this.View.Window, (result) =>
            {
                // Did the user confirm the deletion?
                if (result == 1000)
                {
                    // Yes, remove the account
                    Datasource.Data.Remove(PersonSelected);
                    PersonSelected = null;
                    EmployeeCollection.ReloadData();
                }
            });
        }
コード例 #29
0
        public override NSView GetViewForItem(NSTableView tableView, NSTableColumn tableColumn, nint row)
        {
            NSTableCellView view = (NSTableCellView)tableView.MakeView(tableColumn.Title, this);

            //if (view == null) //Need to recreate entire table if new books added
            if (true)
            {
                view = new NSTableCellView();

                // Configure the view
                view.Identifier = tableColumn.Title;

                // Take action based on title
                switch (tableColumn.Title)
                {
                case "Media":
                    ////view.ImageView = new NSImageView(new CGRect(0, 0, 16, 16));
                    //view.AddSubview(view.ImageView);
                    view.TextField = new NSTextField(new CGRect(20, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Title":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Creator":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Language":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Rating":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Date":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Completion":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Delete":
                    // Create new button
                    var button = new NSButton(new CGRect(0, 0, 81, 16));
                    button.SetButtonType(NSButtonType.MomentaryPushIn);
                    button.Title = "Delete";
                    button.Tag   = row;

                    // Wireup events
                    button.Activated += (sender, e) => {
                        // Get button and product
                        var btn    = sender as NSButton;
                        var record = DataSource.MediaRecords[(int)btn.Tag];

                        // Configure alert
                        var alert = new NSAlert()
                        {
                            AlertStyle      = NSAlertStyle.Informational,
                            InformativeText = $"Are you sure you want to delete the {record.Media.ToLower()} {record.Title} by {record.Creator}? This operation cannot be undone.",
                            MessageText     = $"Delete {record.Title}?",
                        };
                        alert.AddButton("Cancel");
                        alert.AddButton("Delete");
                        alert.BeginSheetForResponse(Controller.View.Window, (result) => {
                            // Should we delete the requested row?
                            if (result == 1001)
                            {
                                // Delete record from the database and remove the given row from the dataset
                                var connection = GetDatabaseConnection();
                                DataSource.MediaRecords[(int)btn.Tag].Delete(connection);
                                DataSource.MediaRecords.RemoveAt((int)btn.Tag);
                                //Controller.ReloadMediaTable();
                                Controller.SearchMedia();
                            }
                        });
                    };
                    // Add to view
                    view.AddSubview(button);
                    break;
                }
            }

            // Setup view based on the column selected
            switch (tableColumn.Title)
            {
            case "Media":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Media;
                break;

            case "Title":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Title;
                break;

            case "Creator":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Creator;
                break;

            case "Language":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Language;
                break;

            case "Rating":
                int rating = DataSource.MediaRecords[(int)row].Rating;
                if (rating == 0)
                {
                    view.TextField.StringValue = "";
                }
                else
                {
                    view.TextField.StringValue = rating.ToString();
                }
                break;

            case "Date":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Date;
                break;

            case "Completion":
                view.TextField.StringValue = DataSource.MediaRecords[(int)row].Status;
                break;

            case "Delete":
                foreach (NSView subview in view.Subviews)
                {
                    var btn = subview as NSButton;
                    if (btn != null)
                    {
                        btn.Tag = row;
                    }
                }
                break;
            }

            return(view);
        }
コード例 #30
0
		public override NSView GetViewForItem (NSTableView tableView, NSTableColumn tableColumn, nint row)
		{

			// This pattern allows you reuse existing views when they are no-longer in use.
			// If the returned view is null, you instance up a new view
			// If a non-null view is returned, you modify it enough to reflect the new data
			NSTableCellView view = (NSTableCellView)tableView.MakeView (tableColumn.Title, this);
			if (view == null) {
				view = new NSTableCellView ();

				// Configure the view
				view.Identifier = tableColumn.Title;

				// Take action based on title
				switch (tableColumn.Title) {
				case "Product":
					view.ImageView = new NSImageView (new CGRect (0, 0, 16, 16));
					view.AddSubview (view.ImageView);
					view.TextField = new NSTextField (new CGRect (20, 0, 400, 16));
					ConfigureTextField (view, row);
					break;
				case "Details":
					view.TextField = new NSTextField (new CGRect (0, 0, 400, 16));
					ConfigureTextField (view, row);
					break;
				case "Action":
					// Create new button
					var button = new NSButton (new CGRect (0, 0, 81, 16));
					button.SetButtonType (NSButtonType.MomentaryPushIn);
					button.Title = "Delete";
					button.Tag = row;

					// Wireup events
					button.Activated += (sender, e) => {
						// Get button and product
						var btn = sender as NSButton;
						var product = DataSource.Products [(int)btn.Tag];

						// Configure alert
						var alert = new NSAlert () {
							AlertStyle = NSAlertStyle.Informational,
							InformativeText = $"Are you sure you want to delete {product.Title}? This operation cannot be undone.",
							MessageText = $"Delete {product.Title}?",
						};
						alert.AddButton ("Cancel");
						alert.AddButton ("Delete");
						alert.BeginSheetForResponse (Controller.View.Window, (result) => {
							// Should we delete the requested row?
							if (result == 1001) {
								// Remove the given row from the dataset
								DataSource.Products.RemoveAt((int)btn.Tag);
								Controller.ReloadTable ();
							}
						});
					};

					// Add to view
					view.AddSubview (button);
					break;
				}

			}

			// Setup view based on the column selected
			switch (tableColumn.Title) {
			case "Product":
				view.ImageView.Image = NSImage.ImageNamed ("tag.png");
				view.TextField.StringValue = DataSource.Products [(int)row].Title;
				view.TextField.Tag = row;
				break;
			case "Details":
				view.TextField.StringValue = DataSource.Products [(int)row].Description;
				view.TextField.Tag = row;
				break;
			case "Action":
				foreach (NSView subview in view.Subviews) {
					var btn = subview as NSButton;
					if (btn != null) {
						btn.Tag = row;
					}
				}
				break;
			}

			return view;
		}
コード例 #31
0
ファイル: AlertSheet.cs プロジェクト: littlefeihu/checktask
 public static void Run(NSAlert alert)
 {
     alert.BeginSheetForResponse(NSApplication.SharedApplication.KeyWindow, response => ShowResponse(alert, response));
 }
コード例 #32
0
		void Run (NSAlert alert)
		{
			switch (AlertOptions.SelectedTag) {
			case 0:
				alert.BeginSheetForResponse (Window, response => ShowResponse (alert, response));
				break;
			case 1:
				ShowResponse (alert, (int)alert.RunSheetModal (Window));
				break;
			case 2:
				ShowResponse (alert, (int)alert.RunModal ());
				break;
			default:
				ResultLabel.StringValue = "Unknown Alert Option";
				break;
			}
		}
コード例 #33
0
        /// <summary>
        /// Begins an asynchronous operation showing a dialog.
        /// </summary>
        /// <returns>An object that represents the asynchronous operation.
        /// For more on the async pattern, see Asynchronous programming in the Windows Runtime.</returns>
        /// <remarks>In some cases, such as when the dialog is closed by the system out of your control, your result can be an empty command.
        /// Returns either the command selected which destroyed the dialog, or an empty command.
        /// For example, a dialog hosted in a charms window will return an empty command if the charms window has been dismissed.</remarks>
        public Task <IUICommand> ShowAsync()
        {
            if (Commands.Count > MaxCommands)
            {
                throw new InvalidOperationException();
            }

#if __ANDROID__
            Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity);
            Android.App.AlertDialog         dialog  = builder.Create();
            dialog.SetTitle(Title);
            dialog.SetMessage(Content);
            if (Commands.Count == 0)
            {
                dialog.SetButton(-1, Resources.System.GetString(Android.Resource.String.Cancel), new EventHandler <Android.Content.DialogClickEventArgs>(Clicked));
            }
            else
            {
                for (int i = 0; i < Commands.Count; i++)
                {
                    dialog.SetButton(-1 - i, Commands[i].Label, new EventHandler <Android.Content.DialogClickEventArgs>(Clicked));
                }
            }
            dialog.Show();

            return(Task.Run <IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            }));
#elif __IOS__ || __TVOS__
            uac = UIAlertController.Create(Title, Content, UIAlertControllerStyle.Alert);
            if (Commands.Count == 0)
            {
                uac.AddAction(UIAlertAction.Create("Close", UIAlertActionStyle.Cancel | UIAlertActionStyle.Default, ActionClicked));
            }
            else
            {
                for (int i = 0; i < Commands.Count; i++)
                {
                    UIAlertAction action = UIAlertAction.Create(Commands[i].Label, CancelCommandIndex == i ? UIAlertActionStyle.Cancel : UIAlertActionStyle.Default, ActionClicked);
                    uac.AddAction(action);
                }
            }
            UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController;
            while (currentController.PresentedViewController != null)
            {
                currentController = currentController.PresentedViewController;
            }

            currentController.PresentViewController(uac, true, null);

            return(Task.Run <IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            }));
#elif __MAC__
            NSAlert alert = new NSAlert();
            alert.AlertStyle      = NSAlertStyle.Informational;
            alert.InformativeText = Content;
            alert.MessageText     = Title;

            foreach (IUICommand command in Commands)
            {
                var button = alert.AddButton(command.Label);
            }

            alert.BeginSheetForResponse(NSApplication.SharedApplication.MainWindow, NSAlert_onEnded);

            return(Task.Run <IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            }));
#elif WINDOWS_PHONE
            List <string> buttons = new List <string>();
            foreach (IUICommand uic in Commands)
            {
                buttons.Add(uic.Label);
            }

            if (buttons.Count == 0)
            {
                buttons.Add("Close");
            }

            MessageDialogAsyncOperation asyncOperation = new MessageDialogAsyncOperation(this);

            string contentText = Content;

            // trim message body to 255 chars
            if (contentText.Length > 255)
            {
                contentText = contentText.Substring(0, 255);
            }

            while (Microsoft.Xna.Framework.GamerServices.Guide.IsVisible)
            {
                Thread.Sleep(100);
            }

            Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox(
                string.IsNullOrEmpty(Title) ? " " : Title,
                contentText,
                buttons,
                DefaultCommandIndex == uint.MaxValue ? 0 : (int)DefaultCommandIndex, // can choose which button has the focus
                Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.None,           // can play sounds
                result =>
            {
                int?returned = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(result);

                // process and fire the required handler
                if (returned.HasValue)
                {
                    if (Commands.Count > returned.Value)
                    {
                        IUICommand theCommand = Commands[returned.Value];
                        asyncOperation.SetResults(theCommand);
                        if (theCommand.Invoked != null)
                        {
                            theCommand.Invoked(theCommand);
                        }
                    }
                    else
                    {
                        asyncOperation.SetResults(null);
                    }
                }
                else
                {
                    asyncOperation.SetResults(null);
                }
            }, null);

            return(asyncOperation.AsTask <IUICommand>());
#elif WINDOWS_UWP
            if (Commands.Count < 3 && Windows.Foundation.Metadata.ApiInformation.IsApiContractPresent("Windows.UI.ApplicationSettings.ApplicationsSettingsContract", 1))
            {
                Windows.UI.Xaml.Controls.ContentDialog cd = new Windows.UI.Xaml.Controls.ContentDialog();
                cd.Title   = Title;
                cd.Content = Content;
                if (Commands.Count == 0)
                {
                    cd.PrimaryButtonText = "Close";
                }
                else
                {
                    cd.PrimaryButtonText   = Commands[0].Label;
                    cd.PrimaryButtonClick += Cd_PrimaryButtonClick;
                    if (Commands.Count > 1)
                    {
                        cd.SecondaryButtonText   = Commands[1].Label;
                        cd.SecondaryButtonClick += Cd_SecondaryButtonClick;
                    }
                }

                return(Task.Run <IUICommand>(async() =>
                {
                    ManualResetEvent mre = new ManualResetEvent(false);
                    IUICommand command = null;

                    await cd.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                    {
                        ContentDialogResult dr = await cd.ShowAsync();
                        if (Commands.Count > 0)
                        {
                            switch (dr)
                            {
                            case ContentDialogResult.Primary:
                                command = Commands[0];
                                if (Commands[0].Invoked != null)
                                {
                                    Commands[0].Invoked.Invoke(Commands[0]);
                                }
                                break;

                            case ContentDialogResult.Secondary:
                                command = Commands[1];
                                if (Commands[1].Invoked != null)
                                {
                                    Commands[1].Invoked.Invoke(Commands[1]);
                                }
                                break;
                            }
                        }
                    });

                    mre.WaitOne();

                    return command;
                }));
            }
            else
            {
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(Content, Title);
                foreach (IUICommand command in Commands)
                {
                    dialog.Commands.Add(new Windows.UI.Popups.UICommand(command.Label, (c) => { command.Invoked(command); }, command.Id));
                }
                return(Task.Run <IUICommand>(async() => {
                    Windows.UI.Popups.IUICommand command = await dialog.ShowAsync();
                    if (command != null)
                    {
                        int i = 0;
                        foreach (Windows.UI.Popups.IUICommand c in dialog.Commands)
                        {
                            if (command == c)
                            {
                                break;
                            }

                            i++;
                        }

                        return Commands[i];
                    }
                    return null;
                }));
            }
#elif WIN32
            return(Task.Run <IUICommand>(() =>
            {
                IUICommand cmd = ShowTaskDialog();
                if (cmd != null)
                {
                    cmd.Invoked?.Invoke(cmd);
                }

                return cmd;
            }));
#else
            throw new PlatformNotSupportedException();
#endif
        }
コード例 #34
0
        public override NSView GetViewForItem(NSTableView tableView, NSTableColumn tableColumn, nint row)
        {
            // This pattern allows you reuse existing views when they are no-longer in use.
            // If the returned view is null, you instance up a new view
            // If a non-null view is returned, you modify it enough to reflect the new data
            NSTableCellView view = (NSTableCellView)tableView.MakeView(tableColumn.Title, this);

            if (view == null)
            {
                view = new NSTableCellView();

                // Configure the view
                view.Identifier = tableColumn.Title;

                // Take action based on title
                switch (tableColumn.Title)
                {
                case "Product":
                    view.ImageView = new NSImageView(new CGRect(0, 0, 16, 16));
                    view.AddSubview(view.ImageView);
                    view.TextField = new NSTextField(new CGRect(20, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Details":
                    view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                    ConfigureTextField(view, row);
                    break;

                case "Action":
                    // Create new button
                    var button = new NSButton(new CGRect(0, 0, 81, 16));
                    button.SetButtonType(NSButtonType.MomentaryPushIn);
                    button.Title = "Delete";
                    button.Tag   = row;

                    // Wireup events
                    button.Activated += (sender, e) => {
                        // Get button and product
                        var btn     = sender as NSButton;
                        var product = DataSource.Products [(int)btn.Tag];

                        // Configure alert
                        var alert = new NSAlert()
                        {
                            AlertStyle      = NSAlertStyle.Informational,
                            InformativeText = $"Are you sure you want to delete {product.Title}? This operation cannot be undone.",
                            MessageText     = $"Delete {product.Title}?",
                        };
                        alert.AddButton("Cancel");
                        alert.AddButton("Delete");
                        alert.BeginSheetForResponse(Controller.View.Window, (result) => {
                            // Should we delete the requested row?
                            if (result == 1001)
                            {
                                // Remove the given row from the dataset
                                DataSource.Products.RemoveAt((int)btn.Tag);
                                Controller.ReloadTable();
                            }
                        });
                    };

                    // Add to view
                    view.AddSubview(button);
                    break;
                }
            }

            // Setup view based on the column selected
            switch (tableColumn.Title)
            {
            case "Product":
                view.ImageView.Image       = NSImage.ImageNamed("tag.png");
                view.TextField.StringValue = DataSource.Products [(int)row].Title;
                view.TextField.Tag         = row;
                break;

            case "Details":
                view.TextField.StringValue = DataSource.Products [(int)row].Description;
                view.TextField.Tag         = row;
                break;

            case "Action":
                foreach (NSView subview in view.Subviews)
                {
                    var btn = subview as NSButton;
                    if (btn != null)
                    {
                        btn.Tag = row;
                    }
                }
                break;
            }

            return(view);
        }
コード例 #35
0
ファイル: MainWindow.cs プロジェクト: pbbpage/mac-samples
		void ShowAlert (NSObject sender) {
			if (ShowAlertAsSheet) {
				var input = new NSTextField (new CGRect (0, 0, 300, 20));

				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Informational,
					InformativeText = "This is the body of the alert where you describe the situation and any actions to correct it.",
					MessageText = "Alert Title",
				};
				alert.AddButton ("Ok");
				alert.AddButton ("Cancel");
				alert.AddButton ("Maybe");
				alert.ShowsSuppressionButton = true;
				alert.AccessoryView = input;
				alert.Layout ();
				alert.BeginSheetForResponse (this, (result) => {
					Console.WriteLine ("Alert Result: {0}, Suppress: {1}", result, alert.SuppressionButton.State == NSCellStateValue.On);
				});
			} else {
				var input = new NSTextField (new CGRect (0, 0, 300, 20));

				var alert = new NSAlert () {
					AlertStyle = NSAlertStyle.Informational,
					InformativeText = "This is the body of the alert where you describe the situation and any actions to correct it.",
					MessageText = "Alert Title",
				};
				alert.AddButton ("Ok");
				alert.AddButton ("Cancel");
				alert.AddButton ("Maybe");
				alert.ShowsSuppressionButton = true;
				alert.AccessoryView = input;
				alert.Layout ();
				var result = alert.RunModal ();
				Console.WriteLine ("Alert Result: {0}, Suppress: {1}", result, alert.SuppressionButton.State == NSCellStateValue.On);
			}
		}
コード例 #36
0
ファイル: MessageDialog.cs プロジェクト: inthehand/Charming
        /// <summary>
        /// Begins an asynchronous operation showing a dialog.
        /// </summary>
        /// <returns>An object that represents the asynchronous operation.
        /// For more on the async pattern, see Asynchronous programming in the Windows Runtime.</returns>
        /// <remarks>In some cases, such as when the dialog is closed by the system out of your control, your result can be an empty command.
        /// Returns either the command selected which destroyed the dialog, or an empty command.
        /// For example, a dialog hosted in a charms window will return an empty command if the charms window has been dismissed.</remarks>
        public Task<IUICommand> ShowAsync()
        {
            if (Commands.Count > MaxCommands)
            {
                throw new InvalidOperationException();
            }

#if __ANDROID__
            Android.App.AlertDialog.Builder builder = new Android.App.AlertDialog.Builder(Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity);
            Android.App.AlertDialog dialog = builder.Create();
            dialog.SetTitle(Title);
            dialog.SetMessage(Content);
            if (Commands.Count == 0)
            {
                dialog.SetButton(-1, Resources.System.GetString(Android.Resource.String.Cancel), new EventHandler<Android.Content.DialogClickEventArgs>(Clicked));
            }
            else
            {
                for (int i = 0; i < Commands.Count; i++)
                {
                    dialog.SetButton(-1 - i, Commands[i].Label, new EventHandler<Android.Content.DialogClickEventArgs>(Clicked));
                }
            }
            dialog.Show();

            return Task.Run<IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            });

#elif __IOS__ || __TVOS__
            uac = UIAlertController.Create(Title, Content, UIAlertControllerStyle.Alert);
            if (Commands.Count == 0)
            {
                uac.AddAction(UIAlertAction.Create("Close", UIAlertActionStyle.Cancel | UIAlertActionStyle.Default, ActionClicked));
            }
            else
            {
                for (int i = 0; i < Commands.Count; i++)
                {
                    UIAlertAction action = UIAlertAction.Create(Commands[i].Label, CancelCommandIndex == i ? UIAlertActionStyle.Cancel : UIAlertActionStyle.Default, ActionClicked);
                    uac.AddAction(action);
                }
            }
            UIViewController currentController = UIApplication.SharedApplication.KeyWindow.RootViewController;
            while (currentController.PresentedViewController != null)
                currentController = currentController.PresentedViewController;
            
            currentController.PresentViewController(uac, true, null);

            return Task.Run<IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            });

#elif __MAC__
            NSAlert alert = new NSAlert();
            alert.AlertStyle = NSAlertStyle.Informational;
            alert.InformativeText = Content;
            alert.MessageText = Title;

            foreach(IUICommand command in Commands)
            {
                var button = alert.AddButton(command.Label);
            }

            alert.BeginSheetForResponse(NSApplication.SharedApplication.MainWindow, NSAlert_onEnded);

            return Task.Run<IUICommand>(() =>
            {
                _handle.WaitOne();
                return _selectedCommand;
            });

#elif WINDOWS_PHONE
            List<string> buttons = new List<string>();
            foreach(IUICommand uic in this.Commands)
            {
                buttons.Add(uic.Label);
            }

            if (buttons.Count == 0)
            {
                buttons.Add("Close");
            }

            MessageDialogAsyncOperation asyncOperation = new MessageDialogAsyncOperation(this);

            string contentText = Content;

            // trim message body to 255 chars
            if (contentText.Length > 255)
            {
                contentText = contentText.Substring(0, 255);
            }
            
            while(Microsoft.Xna.Framework.GamerServices.Guide.IsVisible)
            {
                Thread.Sleep(250);
            }

            Microsoft.Xna.Framework.GamerServices.Guide.BeginShowMessageBox(
                        string.IsNullOrEmpty(Title) ? " " : Title,
                        contentText,
                        buttons,
                        (int)DefaultCommandIndex, // can choose which button has the focus
                        Microsoft.Xna.Framework.GamerServices.MessageBoxIcon.None, // can play sounds
                        result =>
                        {
                            int? returned = Microsoft.Xna.Framework.GamerServices.Guide.EndShowMessageBox(result);
                            
                            // process and fire the required handler
                            if (returned.HasValue)
                            {
                                if (Commands.Count > returned.Value)
                                {
                                    IUICommand theCommand = Commands[returned.Value];
                                    asyncOperation.SetResults(theCommand);
                                    if (theCommand.Invoked != null)
                                    {
                                        theCommand.Invoked(theCommand);
                                    }
                                }
                                else
                                {
                                    asyncOperation.SetResults(null);
                                }
                            }
                            else
                            {
                                asyncOperation.SetResults(null);
                            }
                        }, null);

            return asyncOperation.AsTask<IUICommand>();
#elif WINDOWS_UWP
            if (Commands.Count < 3 && Windows.Foundation.Metadata.ApiInformation.IsApiContractPresent("Windows.UI.ApplicationSettings.ApplicationsSettingsContract", 1))
            {
                Windows.UI.Xaml.Controls.ContentDialog cd = new Windows.UI.Xaml.Controls.ContentDialog();
                cd.Title = Title;
                cd.Content = Content;
                if(Commands.Count == 0)
                {
                    cd.PrimaryButtonText = "Close";
                }
                else
                {
                    cd.PrimaryButtonText = Commands[0].Label;
                    cd.PrimaryButtonClick += Cd_PrimaryButtonClick;
                    if(Commands.Count > 1)
                    {
                        cd.SecondaryButtonText = Commands[1].Label;
                        cd.SecondaryButtonClick += Cd_SecondaryButtonClick;
                    }
                }
                
                return Task.Run<IUICommand>(async () => 
                {
                    ManualResetEvent mre = new ManualResetEvent(false);
                    IUICommand command = null;

                    await cd.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async () =>
                    {
                        ContentDialogResult dr = await cd.ShowAsync();
                        if (Commands.Count > 0)
                        {
                            switch (dr)
                            {
                                case ContentDialogResult.Primary:
                                    command = Commands[0];
                                    if(Commands[0].Invoked != null)
                                    {
                                        Commands[0].Invoked.Invoke(Commands[0]);
                                    }
                                    break;

                                case ContentDialogResult.Secondary:
                                    command = Commands[1];
                                    if (Commands[1].Invoked != null)
                                    {
                                        Commands[1].Invoked.Invoke(Commands[1]);
                                    }
                                    break;
                            }
                        }
                    });

                    mre.WaitOne();

                    return command;
                });
            }
            else
            {
                Windows.UI.Popups.MessageDialog dialog = new Windows.UI.Popups.MessageDialog(Content, Title);
                foreach (IUICommand command in Commands)
                {
                    dialog.Commands.Add(new Windows.UI.Popups.UICommand(command.Label, (c)=> { command.Invoked(command); }, command.Id));
                }
                return Task.Run<IUICommand>(async () => {
                    Windows.UI.Popups.IUICommand command = await dialog.ShowAsync();
                    if (command != null)
                    {
                        int i = 0;
                        foreach(Windows.UI.Popups.IUICommand c in dialog.Commands)
                        {
                            if(command == c)
                            {
                                break;
                            }

                            i++;
                        }

                        return Commands[i];
                    }
                    return null;
                });
            }
#elif WIN32
            return Task.Run<IUICommand>(() =>
            {
                IUICommand cmd = ShowTaskDialog();
                if (cmd != null)
                {
                    cmd.Invoked?.Invoke(cmd);
                }

                return cmd;
            });
#else
            throw new PlatformNotSupportedException();
#endif
        }
コード例 #37
0
        public override NSView GetViewForItem(NSTableView tableView, NSTableColumn tableColumn, nint row)
        {
            // This pattern allows you reuse existing views when they are no-longer in use.
            // If the returned view is null, you instance up a new view
            // If a non-null view is returned, you modify it enough to reflect the new data
            NSTableCellView view = (NSTableCellView)tableView.MakeView(tableColumn.Title, this);

            view = new NSTableCellView();
            var showPassword = DataSource.Records[(int)row].ShowPassword;

            // Configure the view
            view.Identifier = tableColumn.Title;

            // Take action based on title
            switch (tableColumn.Title)
            {
            case "Website/Service":
            case "Account Name":
                view.TextField = new NSTextField(new CGRect(0, 0, 400, 16));
                ConfigureTextField(view, row);
                break;

            case "Password":
                view.TextField = showPassword ? new NSTextField(new CGRect(0, 0, 400, 16)) : new NSSecureTextField(new CGRect(0, 0, 400, 16));
                ConfigureTextField(view, row);
                break;

            case "Actions":
                // Create new button
                var removeButton = new NSButton(new CGRect(0, 0, 60, 16));
                removeButton.Tag      = row;
                removeButton.Bordered = false;
                removeButton.Cell     = new NSButtonCell {
                    BackgroundColor = NSColor.DarkGray, Title = "Remove"
                };

                // Wireup events
                removeButton.Activated += (sender, e) =>
                {
                    // Get button and product
                    var btn        = sender as NSButton;
                    var record     = DataSource.Records[(int)btn.Tag];
                    var connection = SqliteManager.GetDatabaseConnection();

                    // Configure alert
                    var alert = new NSAlert()
                    {
                        AlertStyle      = NSAlertStyle.Informational,
                        InformativeText = $"Are you sure you want to delete data for {record.Website}? This operation cannot be undone.",
                        MessageText     = $"Delete data for {record.Website}?",
                    };
                    alert.AddButton("Cancel");
                    alert.AddButton("Delete");
                    alert.BeginSheetForResponse(Controller.View.Window, (result) =>
                    {
                        // Should we delete the requested row?
                        if (result == 1001)
                        {
                            // Remove the given row from the dataset
                            DataSource.RemoveRecord(record, connection);
                            Controller.PushView();
                        }
                    });
                };

                view.AddSubview(removeButton);

                var showButton = new NSButton(new CGRect(70, 0, 60, 16));
                showButton.Tag  = row;
                showButton.Cell = new NSButtonCell {
                    BackgroundColor = NSColor.DarkGray, Title = showPassword ? "Hide" : "Show"
                };

                showButton.Activated += (sender, e) =>
                {
                    var btn            = sender as NSButton;
                    var selectedRecord = DataSource.Records[(int)btn.Tag];

                    foreach (var record in DataSource.Records)
                    {
                        record.ShowPassword = false;
                    }

                    selectedRecord.ShowPassword = showPassword ? false : true;
                    Controller.PushView();
                };

                view.AddSubview(showButton);

                var copyButton = new NSButton(new CGRect(140, 0, 60, 16));
                copyButton.Tag  = row;
                copyButton.Cell = new NSButtonCell {
                    BackgroundColor = NSColor.DarkGray, Title = "Copy"
                };

                copyButton.Activated += (sender, e) =>
                {
                    var btn            = sender as NSButton;
                    var selectedRecord = DataSource.Records[(int)btn.Tag];

                    var pasteboard = NSPasteboard.GeneralPasteboard;
                    pasteboard.ClearContents();
                    pasteboard.WriteObjects(new NSString[] { (NSString)selectedRecord.Password });
                };

                view.AddSubview(copyButton);

                var editButton = new NSButton(new CGRect(210, 0, 60, 16));
                editButton.Tag  = row;
                editButton.Cell = new NSButtonCell {
                    BackgroundColor = NSColor.DarkGray, Title = "Edit"
                };

                editButton.Activated += (sender, e) =>
                {
                    var btn            = sender as NSButton;
                    var selectedRecord = DataSource.Records[(int)btn.Tag];
                    var connection     = SqliteManager.GetDatabaseConnection();

                    Controller.RefillRecord(selectedRecord, btn.Tag);
                    DataSource.RemoveRecord(selectedRecord, connection);
                };

                view.AddSubview(editButton);
                break;
            }

            // Setup view based on the column selected
            switch (tableColumn.Title)
            {
            case "Website/Service":
                view.TextField.StringValue = DataSource.Records[(int)row].Website;
                break;

            case "Account Name":
                view.TextField.StringValue = DataSource.Records[(int)row].AccountName;
                break;

            case "Password":
                view.TextField.StringValue = DataSource.Records[(int)row].Password;
                break;

            case "Actions":
                foreach (NSView subview in view.Subviews)
                {
                    var btn = subview as NSButton;
                    if (btn != null)
                    {
                        btn.Tag = row;
                    }
                }
                break;
            }

            return(view);
        }