How can I stop a timer on WP7 from an external event? - windows-phone-7

I need a timer that redirects me to another page after 5 seconds, the problem is that it redirects me to this page every 5 seconds, so I need to stop it. If I stop It after tmr.Start() It doesn't execute the event. How can I do this in the event OnTimerTick?
DispatcherTimer tmr = new DispatcherTimer();
tmr.Interval = TimeSpan.FromSeconds(5);
tmr.Tick += new EventHandler(OnTimerTick);
tmr.Start();
void OnTimerTick(object sender, EventArgs e)
{
NavigationService.Navigate(new Uri("/lvlSet1/s1lvl3.xaml", UriKind.Relative));
}

Description
Two possible solutions.
Create your DispatcherTimer instance on class level, not in your method. Then you can acces them from your OnTimerTick Method.
You can cast the sender to DispatcherTimer in your OnTimerTick method.
Sample
1. Solution
public class YourClass
{
DispatcherTimer tmr = new DispatcherTimer();
public void YourMethodThatStartsTheTimer()
{
tmr.Interval = TimeSpan.FromSeconds(5);
tmr.Tick += new EventHandler(OnTimerTick);
tmr.Start();
}
void OnTimerTick(object sender, EventArgs e)
{
tmr.Stop();
NavigationService.Navigate(new Uri("/lvlSet1/s1lvl3.xaml", UriKind.Relative));
}
}
2. Solution
void OnTimerTick(object sender, EventArgs e)
{
((DispatcherTimer)sender).Stop();
NavigationService.Navigate(new Uri("/lvlSet1/s1lvl3.xaml", UriKind.Relative));
}
More Information
MSDN: DispatcherTimer Class

Trying structuring your code like this. Is is going to keep your timer object in scope so you can stop it after the first tick happens.
class SimpleExample
{
DispatcherTimer timer;
public SimpleExample()
{
timer = new DispatcherTimer();
timer.Interval = TimeSpan.FromSeconds(5);
timer.Tick += new EventHandler(OnTimerTick);
}
public void SomeMethod()
{
timer.Start();
}
void OnTimerTick(object sender, EventArgs e)
{
timer.Stop();
NavigationService.Navigate(new Uri("/lvlSet1/s1lvl3.xaml", UriKind.Relative));
}
}

Related

Xamarin Stopwatch is very slow if smartphone is in locked mode

So i have a small xamarin project. Just a little stopwatch:
public partial class Stopwatch : ContentPage
{
Stopwatch stopwatch;
public Stopwatch()
{
InitializeComponent();
stopwatch = new Stopwatch();
labeltimer.Text = "00:00:00.00";
}
private void btnTimerReset(object sender, EventArgs e)
{
btnStart.Text = "Start";
stopwatch.Reset();
}
private void btnTimerstop(object sender, EventArgs e)
{
if (labeltimer.Text != "00:00:00.00")
btnStart.Text = "Resume";
stopwatch.Stop();
}
private void btnTimerStart(object sender, EventArgs e)
{
Timerstart();
}
private void Timerstart()
{
stopwatch.Start();
Device.StartTimer(TimeSpan.FromMilliseconds(1), () =>
{
labeltimer.Text = stopwatch.Elapsed.ToString("hh\\:mm\\:ss\\.ff");
return true; // return true to repeat counting, false to stop timer
});
}
}
}
My problem is now, that everything works perfectly, until i start the stopwatch and lock my phone. The stopwatch then works very slow.
Any idea, how to fix that?

Close ModalView on back button.(Xamarin)

I am showing a ModalView(Navigation page) on button click.
Its working well. I want to close Modalview on Back button.
If you have any idea guide me.
My code as follows.
Button click event
protected void btnEdit_Click(object sender, EventArgs e)
{
var navigation = new NavigationPage(new Settings());
UIViewController navc = navigation.CreateViewController();
navc.ModalPresentationStyle = UIModalPresentationStyle.FullScreen;
this.PresentViewController(navc, true, null);
}
Setting Form code
[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class Settings : ContentPage
{
public Settings()
{
var backItem = new ToolbarItem
{
Text = "Back"
};
this.ToolbarItems.Add(backItem);
backItem .SetBinding(MenuItem.CommandProperty, "BackClicked");
backItem .Clicked += (object sender, System.EventArgs e) =>
{
**// This code Not working**
Navigation.PopModalAsync(false);
};
InitializeComponent();
}
}
You appear to be mixing native iOS code with Xamarin.Forms code, as #Jason mentions in the comment. To open a modal view from XamForms, you can call Navigation.PushModal():
protected async void btnEdit_Click(object sender, EventArgs e)
{
var navigation = new NavigationPage(new Settings());
await Navigation.PushModalAsync(navigation);
}
Update based on comment
public class MyTabbarPage : TabbarPage
{
...
public void ButtonClicked()
{
var navigation = new NavigationPage(new Settings());
await Navigation.PushModalAsync(navigation);
}
}
// Inside renderer
protected async void btnEdit_Click(object sender, EventArgs e)
{
(Element as MyTabbarPage).ButtonClicked();
}
I did as below code to call XamForms class function an its worked.
protected void btnEdit_Click(object sender, EventArgs e)
{
Maintabpage obj =(Maintabpage)Xamarin.Forms.Application.Current.MainPage;
obj.ButtonClicked();
}

Need slideshow of images when my application is launched in windows phone 7

How to get the slideshow of images with time interval of 2 seconds. I had referred the below code from stackoverflow but while running iam nt getting any images displayed.. Please tel where iam went wrong...
Xaml:
<image Name=myImg Source={Binding bi}/>
Code:
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()
{
Imagesource 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);
}
Thanks in Advance
Change Name=myImg to x:Name="myImg" and remove the Source attribute entirely. Otherwise it looks like it should work.

Getting a concrete event from WP7 calendar

I'm working on a WP7 application and I need it to play the song in the first link if the current event on the calendar is "Meeting". However, with the current code, it plays the second song instead if the first one even though the event is set correctly.
Here is my code:
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Set the data context of the listbox control to the sample data
DataContext = App.ViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
// Load data for the ViewModel Items
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.ViewModel.IsDataLoaded)
{
App.ViewModel.LoadData();
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
Appointments appts = new Appointments();
//Identify the method that runs after the asynchronous search completes.
appts.SearchCompleted += new EventHandler<AppointmentsSearchEventArgs>(Appointments_SearchCompleted);
DateTime start = DateTime.Now;
DateTime end = DateTime.Now;
int max = 1;
//Start the asynchronous search.
appts.SearchAsync(start, end, max, "Appointments Test #1");
textBlock3.Text = DateTime.Now.ToString("hh:mm:ss tt");
}
void Appointments_SearchCompleted(object sender, AppointmentsSearchEventArgs e)
{
try
{
AppointmentResultsDataLINQ.DataContext =
from Appointment appt in e.Results
where appt.IsAllDayEvent == false
select appt;
}
catch (System.Exception)
{
}
}
private void button2_Click(object sender, RoutedEventArgs e)
{
if ((AppointmentResultsDataLINQ.DataContext).Equals("Meeting"))
{
mediaElement1.Source = new Uri("http://www.opendrive.com/files/NV8zNTMwNDYwX2hxRXZR/Crystallize.mp3", UriKind.Absolute);
}
else
{
mediaElement1.Source = new Uri("https://www.opendrive.com/files/NV8zMjAxODY0X0VBNDJY/Hetken%20tie%20on%20kevyt%20(piano%20cover)%20-%20YouTube.mp3", UriKind.Absolute);
}
mediaElement1.Play();
}
}
The problem appears to be this line:
if ((AppointmentResultsDataLINQ.DataContext).Equals("Meeting"))
You're comparing the result of calling the ToString() method on the Appointment instance with the string "Meeting".
You probably want:
if ((AppointmentResultsDataLINQ.DataContext as Appointment).Subject.Equals("Meeting"))
Update
You're actually checking an Enumerable of Appointments.
Here's how to check if any of them are "Meeting":
if ((AppointmentResultsDataLINQ.DataContext as IEnumerable<Appointment>).Any(app => app.Subject.Equals("Meeting")))

How to detect new or modified files

I found there are two ways to approach it, ReadDirectoryChangesW and FindFirstChangeNotification.
I want to know what’s the difference between them, performance or otherwise?
This is tagged for Winapi, but I give it a shot with .net anyway.
You can use the FileSystemWatcher class from System.IO for this.
static void Main(string[] args)
{
FileSystemWatcher fsw = new FileSystemWatcher("C:\\");
fsw.Changed += new FileSystemEventHandler(fsw_Changed);
fsw.Created += new FileSystemEventHandler(fsw_Created);
fsw.Deleted += new FileSystemEventHandler(fsw_Deleted);
fsw.EnableRaisingEvents = true;
fsw.IncludeSubdirectories = true;
fsw.Renamed += new RenamedEventHandler(fsw_Renamed);
Console.Read();
}
static void fsw_Renamed(object sender, RenamedEventArgs e)
{
Console.WriteLine("{0} was changed to {1}", e.OldName, e.Name);
}
static void fsw_Deleted(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was deleted", e.Name);
}
static void fsw_Created(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was created", e.Name);
}
static void fsw_Changed(object sender, FileSystemEventArgs e)
{
Console.WriteLine("{0} was changed", e.Name);
}

Resources