How do I stop my application from going back when the user clicks on the "Cancel" button after hitting the back button?
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel);
if (buttonInfo == MessageBoxResult.OK)
{
this.NavigationService.GoBack();
}
else
{
//How to stop page from navigating
}
}
Use CancelEventArgs to cancel the action, property Cancel.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
// If the event has already been cancelled, do nothing
if(e.Cancel)
return;
var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel);
if (buttonInfo == MessageBoxResult.OK)
{
this.NavigationService.GoBack();
}
else
{
//Stop page from navigating
e.Cancel = true;
}
}
A little more ..
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
if (e.Cancel)
return;
var buttonInfo = MessageBox.Show("Are you sure you want to exit?", "Exit", MessageBoxButton.OKCancel);
if (buttonInfo == MessageBoxResult.OK)
{
**//this line may useful if you are in the very first page of your app**
if (this.NavigationService.CanGoBack)
{
this.NavigationService.GoBack();
}
}
else
{
//Stop page from navigating
e.Cancel = true;
}
}
Related
private void ExitAndSave(object sender, EventArgs e)
{
foreach (Form form in MdiChildren)
{
if (form is TextForm tf)
{
tf.BringToFront();
DialogResult dr = MessageBox.Show("Do you want to save your document?", "Save document?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dr == DialogResult.Yes)
{
//counter++;
var textBoxValue = tf.FetchTextBoxValue();
//string filePath = $"{DateTime.Now.Ticks.ToString()}.txt";
string filePath = $"composition{DateTime.Now.Ticks.ToString()}.txt";
File.WriteAllText(filePath, textBoxValue);
}
if (dr == DialogResult.No)
{
continue;
}
}
else if (form is ImageDocumentForm)
{
MessageBox.Show("Please note that only text documents can be saved.", "Advisory:", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
Close();
}
This code works fine. I need it to be called when the user exits the program. I'm not able to assign this event to the form closing event in the design view.
Your event argument needs to be of the form FormClosingEventArgs e
Change that and try again.
public async void clearswitchHandle_Toggled(object sender,
Xamarin.Forms.ToggledEventArgs e)
{
var yesSelected = await DisplayAlert("WARNING!!!", "Are you sure you want to CLEAR DATA entered", "YES", "NO");
if (yesSelected == true)
{
clearButton.IsEnabled = true;
}
else
{
clearSwitch.IsToggled = false;
}
}
Try to lock this async method, it could be called more than once:
private bool lockAlert;
public async void Handle_Toggled(object sender, Xamarin.Forms.ToggledEventArgs e)
{
if (lockAlert) return;
lockAlert=true;
var ok = await DisplayAlert("WARNING!!!", "Are you sure you want to CLEAR DATA entered", "YES", "NO");
if (ok)
{
clearButton.IsEnabled = true;
}
else
{
clearSwitch.IsToggled = false;
}
lockAlert=false;
}
When i click on the tab page () a new settings page comes on but it's not populated with the info i already entered but it i click on a button (Navigation.PushModalAsync(new SettingsPage());) the page comes on and its populated with info I entered. is there a difference between the two?
//for tab page
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:Bldg"
x:Class="Bldg.HomePage" >
<local:HistoryLogPage Title="Log"/>
<local:AddDrainsPage Title="Add"/>
<local:SettingsPage Title="Edit Settings"/>
<Label x:Name="drain1Label" />
</TabbedPage>
//for click button
void NextpageButton_Clicked(object sender, System.EventArgs e)
{
Navigation.PushModalAsync(new SettingsPage());
}
//SettingsPage
namespace Bldg
{
public partial class SettingsPage : ContentPage
{
public static string item, username;
public static string location1, location2;
bool is1Empty = string.IsNullOrEmpty(Settings.n1LocationSettings);
bool is2Empty = string.IsNullOrEmpty(Settings.n2LocationSettings);
List<string> list;
public SettingsPage()
{
InitializeComponent();
drainquantity();
list = new List<string>();
list.Add("1");
list.Add("2");
locationPicker1.SelectedIndexChanged += drain1Handle_SelectedIndexChanged;
locationPicker2.SelectedIndexChanged += drain2Handle_SelectedIndexChanged;
//nameofpickerinxamlfile.On<iOS().SetUpdateMode(UpdateMode.WhenFinished);
locationPicker1.On<iOS>().SetUpdateMode(UpdateMode.WhenFinished);
locationPicker2.On<iOS>().SetUpdateMode(UpdateMode.WhenFinished);
drainxPicker.SelectedItem = Settings.DrainquantitySettings;
locationPicker1.SelectedItem = Settings.n1LocationSettings;
locationPicker2.SelectedItem = Settings.n2LocationSettings;
nameEntry.Text = Settings.NameSettings;
clearButton.IsVisible = false;
drainlocationPicker2.IsEnabled = false;
drainxPicker.SelectedItem = Settings.DrainquantitySettings;
}
//this is fired when user changes or selects new selection
void drainxHandle_SelectedIndexChanged(object sender, System.EventArgs e)
{
//to get the value of user selected going to be use in switch; then save in a
variable
var drainx = drainxPicker.Items[drainxPicker.SelectedIndex];
item = (string)drainxPicker.SelectedItem;
bool isdrainxEmpty = string.IsNullOrEmpty(Settings.DrainquantitySettings);
if (isdrainxEmpty == true)
{
//switch for user selected in drainpicker
switch (drainx)
{
case "1":
n1Gridrow.IsVisible = true;
locationPicker1.IsVisible = true;
n2Gridrow.IsVisible = false;
if (is1Empty == true)
{
drainxPicker.IsEnabled = true;
}
else
drainxPicker.IsEnabled = false;
break;
case "2":
n1Gridrow.IsVisible = true;
n2Gridrow.IsVisible = true;
locationPicker2.IsEnabled = false;
break;
} //switch end
}
else
{
drainxPicker.IsEnabled = false;
nameEntry.IsEnabled = false;
n1Gridrow.IsVisible = true;
n2Gridrow.IsVisible = true;
locationPicker1.IsEnabled = false;
locationPicker2.IsEnabled = false;
settingsaveButton.IsVisible = false;
}
}
void n1Handle_SelectedIndexChanged(object sender, System.EventArgs e)
{
location1 = (string)locationPicker1.SelectedItem;
if (is1Empty == true)
{
locationPicker2.IsEnabled = true;
n2Label.IsVisible = true;
locationPicker2.Items.Remove((string)locationPicker1.SelectedItem);
}
drainxPicker.IsEnabled = false;
locationPicker1.IsEnabled = false;
}
void n2Handle_SelectedIndexChanged(object sender, System.EventArgs e)
{
location2 = (string)locationPicker2.SelectedItem;
if (is2Empty == true)
{
locationPicker2.IsEnabled = true;
}
drainxPicker.IsEnabled = false;
locationPicker2.IsEnabled = false;
}
void nxy1()
{
foreach (var location in list)
{
locationPicker1.Items.Add(location);
}
}
void nxy2()
{
foreach (var location in list)
{
locationPicker2.Items.Add(location);
}
}
void settingsaveButton_Clicked(object sender, System.EventArgs e)
{
bool isNameEmpty = string.IsNullOrEmpty(nameEntry.Text);
if (isNameEmpty == true)
{
DisplayAlert("Enter Name", "PLEASE", "OK");
}
else
{
Navigation.PushModalAsync(new HomePage());
//saving to Settings
Settings.n1LocationSettings = location1;
Settings.n2LocationSettings = location2;
Settings.NameSettings = username;
Settings.DrainquantitySettings = item;
drainxPicker.IsEnabled = false;
}
}
void entryNameHandle_Unfocused(object sender, Xamarin.Forms.FocusEventArgs e)
{
username = nameEntry.Text;
}
void clearHandle_Clicked(object sender, System.EventArgs e)
{
Settings.ClearAllData();
}
}
}
I expect that when i click on tabbed settings page, i go to the settings page with info entered populated. just like the button click it goes to settings page already populated with user entered.
Generally, tabbed settings page and pushed settings page is the same. They are all new fresh settings page.
From your code, we can see that you are setting the value of Picker by Settings plugin:
drainxPicker.SelectedItem = Settings.DrainquantitySettings;
locationPicker1.SelectedItem = Settings.n1LocationSettings;
locationPicker2.SelectedItem = Settings.n2LocationSettings;
So, whether the info entered will be populated or not when you go to the setting page is depending on the values in Settings.
For example:
If Settings.DrainquantitySettings; has value, then drainxPicker's info will be populated.
Check the Values in your Setting when you go to tabbed settings page and pushed settings page to find any difference.
I have the following code:
private void CloseOrder(object sender, EventArgs e)
{
Android.Support.V7.App.AlertDialog.Builder alert = new Android.Support.V7.App.AlertDialog.Builder(this);
alert.SetTitle("Cerrar Pedido");
alert.SetMessage("Are you sure?");
alert.SetCancelable(true);
alert.SetPositiveButton("Confirm", delegate { this.Rta = true; });
alert.SetNegativeButton("Cancel", delegate { this.Rta = false; });
Dialog dialog = alert.Create();
dialog.Show();
if (this.Rta)
{
//Some code here
}
}
this.Rta is a property of my class.
The problem is that the alert doesn't show at dialog.show(), it shows once the method CloseOrder() ended, so this.Rta never gets the corresponding value assigned.
I've been searching a lot but I can't find a solution, if anyone can help me that'd be great!
dialog.Show() is asynchronous method, that means CloseOrder(object sender, EventArgs e) and dialog.Show() end up at the same time.
You can not get the 'Rta' assigned value at the CloseOrder function.
You will get the value when you click the confirm or cancel button of the dialog.
I suggest you to use message sender in the delegate{this.Rta = true}
For example:
mHandler handler = new mHandler();
Message message = new Message();
message.What = 1;
alert.SetPositiveButton("Confirm", delegate { this.Rta = true; handler.SendMessage(message); });
alert.SetNegativeButton("Cancel", delegate { this.Rta = false; handler.SendMessage(message); });
//....
class mHandler : Handler{
public override void HandleMessage(Message message) {
switch (message.What) {
case 1:
if (this.Rta)
{
//Some code here
}
break;
}
}
}
How to retain the saved isolatedstoragesettings while at application launch
I used exception for termination on backevents :
protected void _BackKeyPress(object sender, CancelEventArgs e)
{
if (MessageBox.Show("Do you want to close the application?", "Q", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("key2", "33r4 ");
}
else
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("Key"))
{
IsolatedStorageSettings.ApplicationSettings["Key"] = App.Current.ViewModel;
}
else
{
IsolatedStorageSettings.ApplicationSettings.Add("Key", App.Current.ViewModel);
}
throw new Exception("ExitApplication");
}
}
I try to save the viewmodel which declares in app.xaml.cs, but cant able to get the isolatedstorage settings value in it, at launch. But It compiles and run successfully.
You need to call the IsolatedStorageSettings.Save method:
protected void _BackKeyPress(object sender, CancelEventArgs e)
{
if (MessageBox.Show("Do you want to close the application?", "Q", MessageBoxButton.OKCancel) != MessageBoxResult.OK)
{
e.Cancel = true;
System.IO.IsolatedStorage.IsolatedStorageSettings.ApplicationSettings.Add("key2", "33r4 ");
IsolatedStorageSettings.Save();
}
else
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("Key"))
{
IsolatedStorageSettings.ApplicationSettings["Key"] = App.Current.ViewModel;
}
else
{
IsolatedStorageSettings.ApplicationSettings.Add("Key", App.Current.ViewModel);
}
IsolatedStorageSettings.Save();
throw new Exception("ExitApplication");
}
}