I am making a voting app and I want the user to be allowed to vote just one time/day. I have a main page and on this page, multiple buttons navigating to different pages (where the user can vote).On the voting "page" I have a button that when is pressed, it uploads the vote into a database, and after it is disabled for some time. However, if I go back and forth (voting page -> main page -> voting page) the button is once again enabled. How can I solve this, so wherever I navigate the button will remain disabled? I write down the code that I use to disable the button on the voting page, but as I said, whenever I leave the page the button will be enabled again.
public void ImageButton_Clicked(object sender, EventArgs e)
{
Timer aTimer = new Timer();
myButton.IsEnabled = false;
aTimer.Interval = 5000; //ms
aTimer.Enabled = true;
aTimer.Elapsed += ATimer_Elapsed;
}
public void ATimer_Elapsed(object sender, ElapsedEventArgs e)
{
Device.BeginInvokeOnMainThread(() => { myButton.IsEnabled = true; });
}
The Xaml definition of the button.
<ImageButton
x:Name="myButton"
Clicked="ImageButton_Clicked" >
I guess that you want to store data when leaving page using Navigation, if yes, I suggest you can use Xamarin.Essentials: Preferences to save current user data.
For MainPage:
private void btn1_Clicked(object sender, EventArgs e)
{
Navigation.PushAsync(new Page15());
}
For VotePage:
public partial class Page15 : ContentPage
{
public DateTime dt;
public Page15()
{
InitializeComponent();
DateTime currentdate = DateTime.Now;
bool haskey = Preferences.ContainsKey("user1");
if(haskey)
{
string date = Preferences.Get("user1", "");
if (date != null)
{
dt = Convert.ToDateTime(date);
TimeSpan timediff = currentdate - dt;
if(timediff.Seconds<10)
{
btnvote.IsEnabled = false;
}
}
}
}
private void btnvote_Clicked(object sender, EventArgs e)
{
dt = DateTime.Now;
//save count into database or local
btnvote.IsEnabled = false;
}
protected override void OnDisappearing()
{
base.OnDisappearing();
string clickdate = dt.ToString();
Preferences.Set("user1", clickdate);
}
}
In my code, I disable Button within 10 seconds of voting, you can use timediff.Days;timediff.Minutes to change datetime difference.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.