Windows Phone - Increment a value - c#

How can I increment a value per second, when I passed it from another page?
Here is some code , where I get the value from the previous page + I added the Timer.
The Problem is that the EventHandler that has to been created for the Tick, can t be set to OnNavigatedTo.
public partial class Page1 : PhoneApplicationPage
{
DispatcherTimer timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(.1) };
public Page1()
{
InitializeComponent();
this.timer.Tick += new EventHandler(OnNavigatedTo);
this.Loaded += new RoutedEventHandler(OnNavigatedTo);
}
private void ButtonToPage1(object sender, RoutedEventArgs e)
{
App app = Application.Current as App;
MessageBox.Show(app.storeValue);
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
int test = (int.Parse(QueryStr));
}

try this:
DispatcherTimer tmr;
int test;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
test = (int.Parse(QueryStr));
LoadTimer();
}
public void LoadTimer()
{
tmr = new DispatcherTimer();
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
tmr.Interval = new TimeSpan(0, 0, 1);
tmr.Tick += tmr_Tick;
tmr.Start();
});
}
void tmr_Tick(object sender, EventArgs e)
{
test++;
TextBlock.Text = test.ToString();
}

It isn't clear why you can't just follow the tutorial linked in your comment. I guess you misunderstand it and tried to handle Tick event using OnNavigatedTo() method. Yes, that won't work and you aren't supposed to do so.
You're supposed to simply attach event handler method in OnNavigatedTo :
private int myNumber;
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string QueryStr = "";
NavigationContext.QueryString.TryGetValue("myNumber", out QueryStr);
myNumber = (int.Parse(QueryStr));
DispatcherTimer newTimer = new DispatcherTimer();
newTimer.Interval = TimeSpan.FromSeconds(1);
//attach event handler method for Tick event
newTimer.Tick += OnTimerTick;
//or attach anonymous method so you don't need OnTimerTick() method :
//newTimer.Tick += (o, e) => { myNumber++; };
newTimer.Start();
}
void OnTimerTick(Object sender, EventArgs args)
{
myNumber++;
}

Related

Timer variable is null which is declared for countdown timer?

I have this code which is used for countdown in C#. I can't seem to find why my variable t is null. I tried this code on a separate project and it works well. I tried to incorporate it into another project and it says that variable t is null.
public partial class tracker : Form
{
System.Timers.Timer t;
int h1, m1, s1;
public tracker()
{
InitializeComponent();
}
private void tracker_Load(object sender, EventArgs e)
{
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEventWork;
}
private void btnLogin_Click(object sender, EventArgs e)
{
t.Start();
btnLogin.Enabled = false;
richTextBox1.SelectionLength = 0;
richTextBox1.SelectedText = DateTime.Now.ToString("MM/dd/yyyy\n");
richTextBox2.SelectedText = "Time In\n";
richTextBox3.SelectedText = DateTime.Now.ToString("HH:mm:ss\n");
richTextBox4.SelectedText = "\n";
richTextBox5.SelectedText = "\n";
}
}
You are getting error t as null, because t.Start() is calling before instantiation of Timer object t.
To solve this issue, either instantiate before t.start() or create an object inside the constructor.
Like
public tracker()
{
InitializeComponent();
//Here you can instantiate Timer class
t = new System.Timers.Timer();
t.Interval = 1000; //1s
t.Elapsed += OnTimeEventWork;
}
private void tracker_Load(object sender, EventArgs e)
{
//Do NOT create object of Timer class here
}
private void btnLogin_Click(object sender, EventArgs e)
{
t.Start();
...
}

How to make a label change its text every some time in C# windows forms

I have a label that I want to update every 5 seconds. It should change from 1921 to 1922 onward till 1992. I have tried using a timer but it gave me an error about being accessed on the wrong thread. The code I used was:
public partial class Form1 : Form
{
int x = 1921;
public Form1()
{
InitializeComponent();
}
System.Timers.Timer myTimer = new System.Timers.Timer(1000);
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
label1.Text = x.ToString();
x += 1;
}
private void Form1_Load(object sender, EventArgs e)
{
myTimer.Elapsed += UpdateLabel;
myTimer.Start();
}
}
Try this:
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
//Invoke makes the UI thread call the delegate.
Invoke((MethodInvoker)delegate {label1.Text = x.ToString(); });
x += 1;
}
try this
private readonly object y = new object();
int x = 1921;
public Form1()
{
InitializeComponent();
}
System.Timers.Timer myTimer = new System.Timers.Timer(1000);
private void UpdateLabel(object sender, ElapsedEventArgs e)
{
Invoke((MethodInvoker)(() => { lock (y) { label1.Text = x.ToString(); x++; } }));
}
private void Form1_Load(object sender, EventArgs e)
{
myTimer.Elapsed += UpdateLabel;
myTimer.Start();
}

combination of MouseDown and timer

I try to load a function like "holdFunction", during touching(MouseDown) and during at max 1 second .
So when user try to touch and hold for a second I have to call the function, and this isn't related to mouseUp.
Maybe I must to combine these:
private DateTime dtHold;
private void EditProduct_MouseDown(object sender, MouseButtonEventArgs e)
{
dtHold = DateTime.Now;
}
private void EditProduct_MouseUp(object sender, MouseButtonEventArgs e)
{
TimeSpan interval = TimeSpan.FromSeconds(1);
if (DateTime.Now.Subtract(dtHold) > interval)
{
//HoldFunction();
}
}
and
System.Windows.Threading.DispatcherTimer dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
private void EditProduct_MouseDown(object sender, MouseButtonEventArgs e)
{
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0, 0, 0,1,0);
dispatcherTimer.Start();
}
private int _sec = 0;
private void dispatcherTimer_Tick(object sender, EventArgs e)
{
_sec = _sec + 1;
if (_sec == 2)
{
dispatcherTimer.Stop();
{
//HoldFunction();
}
_sec = 0;
return;
}
}
Is this what you are looking for?
If the User holds the MouseDown for 1 second, the evnt is fired?
public partial class Window2 : Window
{
private DispatcherTimer _DispatcherTimer = new DispatcherTimer();
public Window2()
{
InitializeComponent();
MouseDown += _MouseDown;
MouseUp += _MouseUp;
_DispatcherTimer.Interval = TimeSpan.FromSeconds(1.0);
_DispatcherTimer.Tick += _DispatcherTimer_Tick;
}
private void _DispatcherTimer_Tick(object sender, EventArgs e)
{
_DispatcherTimer.Stop();
Title = DateTime.Now.ToString();
}
private void _MouseUp(object sender, MouseButtonEventArgs e)
{
_DispatcherTimer.Stop();
}
private void _MouseDown(object sender, MouseButtonEventArgs e)
{
_DispatcherTimer.Start();
}
}

Countdown timer using System.Timers.Timer in WPF application [duplicate]

How can I implement the following in my piece of code written in WPF C#?
I have a ElementFlow control in which I have implemented a SelectionChanged event which (by definition) fires up a specific event when the control's item selection has changed.
What I would like it to do is:
Start a timer
If the timer reaches 2 seconds then launch a MessageBox saying ("Hi there") for example
If the selection changes before the timer reaches 2 seconds then the timer should be reset and started over again.
This is to ensure that the lengthy action only launches if the selection has not changed within 2 seconds but I am not familiar with the DispatcherTimer feature of WPF as i am more in the know when it comes to the normal Timer of Windows Forms.
Thanks,
S.
Try this:
private int timerTickCount = 0;
private bool hasSelectionChanged = false;
private DispatcherTimer timer;
In your constructor or relevant method:
timer = new DispatcherTimer();
timer.Interval = new TimeSpan(0, 0, 1); // will 'tick' once every second
timer.Tick += new EventHandler(Timer_Tick);
timer.Start();
And then an event handler:
private void Timer_Tick(object sender, EventArgs e)
{
DispatcherTimer timer = (DispatcherTimer)sender;
if (++timerTickCount == 2)
{
if (hasSelectionChanged) timer.Stop();
else MessageBox.Show("Hi there");
}
}
Finally, to make this work, you just need to set the hasSelectionChanged variable when the selection has changed according to your SelectionChanged event.
I've figured the complete code out as such:
DispatcherTimer _timer;
public MainWindow()
{
_myTimer = new DispatcherTimer();
_myTimer.Tick += MyTimerTick;
_myTimer.Interval = new TimeSpan(0,0,0,1);
}
private void ElementFlowSelectionChanged(object sender, SelectionChangedEventArgs e)
{
_counter = 0;
_myTimer.Stop();
_myTimer.Interval = new TimeSpan(0, 0, 0, 1);
_myTimer.Start();
}
private int _counter;
public int Counter
{
get { return _counter; }
set
{
_counter = value;
OnPropertyChanged("Counter");
}
}
private void MyTimerTick(object sender, EventArgs e)
{
Counter++;
if (Counter == 2)
{
_myTimer.Stop();
MessageBox.Show(“Reached the 2 second countdown”);
}
}
public event PropertyChangedEventHandler PropertyChanged;
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler e = PropertyChanged;
if (e != null)
{
e(this, new PropertyChangedEventArgs(propertyName));
}
}
look here is the code of how to use DispatherTimer and you can add your own logic in it. that will depends on you..
private void ListBox_SelectionChanged_1(object sender, SelectionChangedEventArgs e)
{
DispatcherTimer timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromMilliseconds(2000);
timer.Tick += timer_Tick;
timer.Start();
}
void timer_Tick(object sender, object e)
{
// show your message here..
}
To use a DispatcherTimer:
private DispatcherTimer _timer;
public void StartTimer()
{
if (_timer == null)
{
_timer = new DispatcherTimer();
_timer.Tick += _timer_Tick;
}
_timer.Interval = TimeSpan.FromSeconds(2);
_timer.Start();
}
void _timer_Tick(object sender, EventArgs e)
{
MessageBox.Show("Hi there");
_timer.Stop();
}
void SelectionChangedEvent()
{
StartTimer();
}

Want to have a slideshow of images on button click in Windows Phone 7

I have stack of images in a grid and i want to implement a slide show for it.I am using Microsoft VS 2010 Express Edition for Windows phone for implemenitng this.Can someone help ? The code is :
using System;
using System.Collections.Generic;
using System.Windows.Threading;
namespace swipe
{
public partial class MainPage : PhoneApplicationPage
{
// private DispatcherTimer tmr = new DispatcherTimer();
private List<string> images = new List<string>();
private int imageIndex = 0;
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
// tmr.Interval = TimeSpan.FromSeconds(5);
// tmr.Tick += new EventHandler(tmr_Tick);
LoadImages();
ShowNextImage();
}
private void LoadImages()
{
images.Add("/images/Hydrangeas.jpg");
images.Add("/images/Jellyfish.jpg");
images.Add("/images/Koala.jpg");
images.Add("/images/Tulips.jpg");
}
private void ShowNextImage()
{
// String bi = new BitmapImage(new Uri(images[imageIndex], UriKind.Relative));
myImg.Source = new BitmapImage(new Uri(images[imageIndex], UriKind.Relative));
imageIndex = (imageIndex + 1) % images.Count;
}
//void tmr_Tick(object sender, EventArgs e)
//{
// ShowNextImage();
//}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
//if (!tmr.IsEnabled)
//{
// tmr.Start();
//}
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
//tmr.Stop();
base.OnNavigatedFrom(e);
}
private void Play_Click(object sender, RoutedEventArgs e)
{
ShowNextImage();
}
}
}
Here's a quick example of one way of doing this. It doesn't use a grid of images but I'm sure you can adjust this as you need to.
Edit: reread the title. If you want this to advance on button click get rid of the timer and call ShowNextImage() in the click event.
The page includes the following XAML:
<Image x:Name="myImg" />
The code behind looks like:
private DispatcherTimer tmr = new DispatcherTimer();
private List<string> images = new List<string>();
private int imageIndex = 0;
public MainPage()
{
InitializeComponent();
Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
tmr.Interval = TimeSpan.FromSeconds(5);
tmr.Tick += new EventHandler(tmr_Tick);
LoadImages();
ShowNextImage();
}
private void LoadImages()
{
// list the files (includede in the XAP file) here
images.Add("/images/filename1.jpg");
images.Add("/images/filename2.jpg");
images.Add("/images/filename3.jpg");
images.Add("/images/filename4.jpg");
}
private void ShowNextImage()
{
var bi = new BitmapImage(new Uri(images[imageIndex], UriKind.Relative));
myImg.Source = bi;
imageIndex = (imageIndex + 1) % images.Count;
}
void tmr_Tick(object sender, EventArgs e)
{
ShowNextImage();
}
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (!tmr.IsEnabled)
{
tmr.Start();
}
base.OnNavigatedTo(e);
}
protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
{
tmr.Stop();
base.OnNavigatedFrom(e);
}
Sample code which shows using a button to advance code can be downloaded from http://cid-cc22250598bf7f04.office.live.com/self.aspx/Public/SlideShowDemo.zip
The easy way is to create a collection of images, and and go to next image in the collection when you go to next page in a pivot page.
A other solution is to create a usercontrol.
Here is a guide how to do it in silverlight ( but not in WP7, but it is very similar ).

Categories

Resources