How to Keep Toggle Button state in Windows phone 8 application? - windows-phone-8

I create a toggle button and its working fine . But problem is that how can i Keep previous toggle activity, I mean when application is exit and reopen, it should display the previous toggle state . Here is my code
XAML:
<toolkit:ToggleSwitch x:Name="toggle" Content="ToggleSwitch is on" Header="ToggleSwitch"/>
CS :
public partial class EnglishSub : PhoneApplicationPage
{
public BanglaSub()
{
InitializeComponent();
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
this.toggle.Content = "ToggleSwitch is off";
}
void toggle_Unchecked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "ToggleSwitch is off";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Red);
MessageBox.Show("Disable");
}
void toggle_Checked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "ToggleSwitch is on";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Green);
MessageBox.Show("Enable");
}
}

You can use IsolatedStorageSetings to store application data. and read it when your app page is loaded again. here is how
public bool GetToggleValue()
{
if (IsolatedStorageSettings.ApplicationSettings.Contains("toggleValue"))
{
return bool.Parse(IsolatedStorageSettings.ApplicationSettings["toggleValue"].ToString());
}
else return false;
}
call above method in your page load to set the toggle value
and set checked unchecked value in the settings in your checked unchecked event handlers here is how
IsolatedStorageSettings.ApplicationSettings.Add("toggleValue", true);
IsolatedStorageSettings.Save();

Related

Toggle Button Checked Property Windows Phone 8

I add a toggle button on Windows Phone 8 . When i checked (on), its save a value in Isolated storage and I check that value in constructor whatever it has a toggle value or null. If there is a toggle value I want to display toggle button checked . But I dont know the property to how to checked it when application is run .
Toggle Button XAML :
<toolkit:ToggleSwitch x:Name="toggle" Content="On" Width="165" FontSize="28" VerticalAlignment="Center" HorizontalAlignment="Right"/>
C# :
public Subscription()
{
InitializeComponent();
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (HasSValue() == "NoValue")
{
// Here i want to Display toggle button unchecked
}
else
{
// Here i want to Display toggle button checked
}
}
void toggle_Unchecked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "Off";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Red);
var appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Remove("toggleValue");
appSettings.Save();
}
void toggle_Checked(object sender, RoutedEventArgs e)
{
this.toggle.Content = "On";
this.toggle.SwitchForeground = new SolidColorBrush(Colors.Green);
MessageBox.Show("R U Sure ?");
var appSettings = IsolatedStorageSettings.ApplicationSettings;
appSettings.Add("toggleValue", "MAHIN");
appSettings.Save();
}
public string HasSValue()
{
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (appSettings.Contains("toggleValue"))
{
return (string) appSettings["toggleValue"];
}
else
{
return "NoValue";
}
}
Try this
if (HasSValue() == "NoValue")
{
this.toggle.IsChecked = false;
}
else
{
this.toggle.IsChecked = true;
}
Hope this helps
Update your Constructor as follows
public Subscription()
{
InitializeComponent();
var appSettings = IsolatedStorageSettings.ApplicationSettings;
if (HasSValue() == "NoValue")
{
// Here i want to Display toggle button unchecked
}
else
{
// Here i want to Display toggle button checked
}
this.toggle.Checked += new EventHandler<RoutedEventArgs>(toggle_Checked);
this.toggle.Unchecked += new EventHandler<RoutedEventArgs>(toggle_Unchecked);
}

Display images in observable collection one after the other as user scrolls in windows phone 8

I have a json array of image URLs added into an observable collection and I want to display the first image on the page such that when a user scrolls horizontally, next or previous images in the array shall display on the screen. Help me achieve this.
Here's how I download the image URLs via json and add them to the observable collection
public event PropertyChangedEventHandler PropertyChanged;
private ObservableCollection<readPageModel> readPages = new ObservableCollection<readPageModel>();
public ObservableCollection<readPageModel> Read_Pages
{
get
{
return readPages;
}
set
{
readPages = value;
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs("Read_Pages"));
}
}
}
public void DownloadData()
{
WebClient client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri("http://########/mob/ranges/id/3/limit/10/offset/0/r_id/6", UriKind.Absolute));
}
private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
try
{
if (!string.IsNullOrEmpty(e.Result))
{
string data = e.Result;
var items = JsonConvert.DeserializeObject<readModel[]>(data);
foreach (var x in items)
{
Read_Pages.Add(x);
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
You can take scrollviwer in the xaml after this within this scrollviewer take stack panel with horizontal orientation. and then from c# code add image control to this stack panel.
You can have one image control in content panel and implement below code :
public Page()
{
InitializeComponent();
GestureListener gestureListener = GestureService.GetGestureListener(ContentPanel);
gestureListener.DragCompleted += gestureListener_DragCompleted;
//set the initial image to Image control
}
void gestureListener_DragCompleted(object sender, DragCompletedGestureEventArgs e)
{
// User flicked towards left
if (e.HorizontalVelocity < 0)
{
// Load the next image if Downloaded
}
// User flicked towards right
if (e.HorizontalVelocity > 0)
{
// Load the previous image
}
}
you would also needed to have one variable for tracking the index of image to be loaded

Windows Phone 8 Page Navigation

I have a problem that I can't really figure out, and I am really desperate now - I've no idea why it's happening:(
So here is the problem: I am writing a kind of Guess that Tune app. The first page is a menu page, that a user can press "Play" button, and he will navigate to a GenreSelectPage where he selects a genre and navigates to a GamePage. I wanted to handle BackButtonPress on GamePage - when a user hits BackButton, he navigates to MainPage, not GenreSelectPage. Here is the code:
private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
{
base.OnBackKeyPress(e);
this.player.Pause();
var result = MessageBox.Show(AppResources.GamePageAlert, "Warning", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
//NavigationService.RemoveBackEntry();
//App.RootFrame.Navigate(new Uri(#"/MainPage.xaml", UriKind.Relative));
}
else
{
this.player.Play();
e.Cancel = true;
}
}
However, I encoountered a big problem here I can't really solve. When I move back to MainMEnu, than go again to GenreSelectPage and choose the same genre, everything is ok - the app navigates to GamePage where there is list of 4 answers. However, if I choose another genre, the listBox at GamePage is populated with 12 or 15 items. On the other hand, when I comment navigation to MainPage and normally go back, everything works alright.
Here is my GenrePage Code:
public GenresPage()
{
InitializeComponent();
this.DataContext = App.ViewModel.GenreHelper;
}
private async void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
this.genresListBox.SelectedIndex = -1;
this.progressBar.Visibility = System.Windows.Visibility.Visible;
this.genresListBox.ItemsSource = await App.ViewModel.GenreHelper.GetGenres();
this.progressBar.Visibility = System.Windows.Visibility.Collapsed;
ClearCollections();
}
private static void ClearCollections()
{
if (App.ViewModel.TracksCollection.Count != 0)
{
App.ViewModel.TracksCollection.Clear();
App.ViewModel.TrackCounter = 0;
}
if (App.ViewModel.AnswerCollection.Count > 0)
{
App.ViewModel.AnswerCollection.Clear();
}
}
private async void NavigateToPlay(object sender, RoutedEventArgs e)
{
if (this.genresListBox.SelectedIndex != -1)
{
this.progressBar.Visibility = System.Windows.Visibility.Visible;
await App.ViewModel.GetSongs();
await App.ViewModel.GetAnswers();
this.progressBar.Visibility = System.Windows.Visibility.Collapsed;
NavigationService.Navigate(new Uri(#"/Views/GamePage.xaml", UriKind.Relative));
}
}
UPDATE
On my GamePage I am only assigning DataContext and duration to MediaElement:
public partial class GamePage : PhoneApplicationPage
{
public GamePage()
{
InitializeComponent();
this.DataContext = App.ViewModel;
}
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
var trackId = App.ViewModel.TracksCollection[App.ViewModel.TrackCounter].Id;
var sampleUri = App.ViewModel.GetSampleUri(trackId);
player.Source = new Uri(sampleUri.AbsoluteUri);
player.Play();
}
private void GetTrackDuration(object sender, RoutedEventArgs e)
{
var player = (MediaElement)sender;
if (player.CurrentState == System.Windows.Media.MediaElementState.Playing)
{
playerSeekBar.Maximum = player.NaturalDuration.TimeSpan.TotalSeconds;
}
}
private void PhoneApplicationPage_BackKeyPress(object sender, CancelEventArgs e)
{
base.OnBackKeyPress(e);
this.player.Pause();
var result = MessageBox.Show(AppResources.GamePageAlert, "Warning", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
//NavigationService.RemoveBackEntry();
//App.RootFrame.Navigate(new Uri(#"/MainPage.xaml", UriKind.Relative));
}
else
{
this.player.Play();
e.Cancel = true;
}
}
}
If anyone can point out what I am doing wrong, I would be really greatful - I am fighting it all day and I have no idea what's causing it.
Thank You very much in advance!!

Navigate to the same View. Why Loaded and OnNavigatedTo events aren't called?

Im doing a cloud App(like Skydrive) in Windows Phone 8 , each time I navigate to a different folder I need to reload the FolderView.xaml page to display the content of this folder and I need to add the view to the back stack then I will be able to back to the previous path...
From now when I try to reload the FolderView from the FolderView.xaml.cs page, none event is called...
I don't understand why ? And if you have a solution you are welcome ...
private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
{
if (App.ElementSelected != null)
{
BdeskElement FolderChoosen = new BdeskElement();
FolderChoosen = App.ElementSelected;
Gridentete.DataContext = FolderChoosen;
GetFiles(FolderChoosen);
}
}
private async void llsElements_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LongListSelector llselement = null;
listElementCollection.Clear();
if (sender != null)
llselement =(LongListSelector)sender;
if(llselement.SelectedItem!=null)
{
BdeskElement bdelement=(BdeskElement)llselement.SelectedItem;
if (bdelement.TypeElement==BdeskElement.BdeskTypeElement.Folder)
{
App.DocLibSelected = null;
App.ElementSelected = bdelement;
// I navigate to the same view here but nothing happens
NavigationService.Navigate(new Uri("/Views/BDocs/FolderView.xaml", UriKind.RelativeOrAbsolute));
}
}
}
To navigate to the same page with a new instance, you must change the Uri. For example:
NavigationService.Navigate(new Uri(String.Format("/Views/BDocs/FolderView.xaml?id={0}", Guid.NewGuid().ToString()), UriKind.Relative));
You can discard that parameter if you don't want/use it.

Deregister the EventHandler in Windows Phone 8 application

I am using this piece of code to register the event and want to de-register Event after completing it's task but don't know how to do problem is that I am using local object for registering event..
code..
public void loadData()
{
//Here client is loacal object..
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(AccessTokenDownloadCompleted);
}
void AccessTokenDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
}
If I understood you correctly, you want to remove your event handler after the download is completed. To remove an event handler, all you need to do is:
client.DownloadStringCompleted -= new DownloadStringCompletedEventHandler(AccessTokenDownloadCompleted);
Note the -= instead of +=.
Place this code where the download completes and you should be fine.
Maybe you can try this:
public void loadData()
{
//Here client is loacal object..
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(AccessTokenDownloadCompleted);
}
void AccessTokenDownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
Client client = sender as Client;
if(client != null)
client.DownloadStringCompleted -= new DownloadStringCompletedEventHandler(AccessTokenDownloadCompleted);
}