Set start page in Windows Phone 8.1 universal app - c#

I need to change start page in my app depending on logged user or not. In Silverlight 8.1 version all what I need to do is delete starting page in manifest file and in App.xaml.cs:
private void Application_Launching(object sender, LaunchingEventArgs e)
{
Uri uriMain = new Uri("/PivotPage.xaml", UriKind.Relative);
Uri uriLogin = new Uri("/MainPage.xaml", UriKind.Relative);
var settings = IsolatedStorageSettings.ApplicationSettings;
if (!settings.Contains("user_id"))
{
RootFrame.Navigate(uriLogin);
}
else
{
RootFrame.Navigate(uriMain);
}
}
But in universal version I can't figure out how can I do it. What I need to do to achive this in WP 8.1universal app?
EDIT:
Found a duplicate Change default startup page for windows phone 8.1 app, sorry

In App.xaml.cs look for
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
// ...
// launch codes
// insert here
// Ensure the current window is active
Window.Current.Activate();
}
My launch code detects to see if they're on the Phone or not, so I have a starting page that is
different for each platform
#if WINDOWS_PHONE_APP
if (!rootFrame.Navigate(typeof(PhonePage), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
#endif
#if WINDOWS_APP
if (!rootFrame.Navigate(typeof(DesktopPage), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
#endif

Related

Xamarin.Forms UWP - Launch app on login

I'm trying to launch my app when the user logs in to Windows. I have the appropriate Extension (StartupTask) set in Package.appxmanifest, and I can get the app to launch when I log in to Windows, as expected. However, the app crashes after showing the Splash screen for about a second or two.
In my App.xaml.cs file, I have overridden the OnLaunched (called when the user launches the app) and OnActivated (called when the system launches the app after Windows login). Both call the same function to initialize my app; however, the app crashes only when the app is initialized from the OnActivated function. When initialized from OnLaunched, it works as expected. Here is the relevant code, from App.xaml.cs:
// Called when the user launches the app
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
// Calling InitializeApp here, the app launches without problem
InitializeApp(e);
}
// Called when the system launches the app after Windows login
protected override void OnActivated(IActivatedEventArgs e)
{
base.OnActivated(e);
// Calling InitializeApp here will cause the app to crash
InitializeApp((LaunchActivatedEventArgs)e);
}
// initialize the app
async void InitializeApp(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
var assembliesToInclude = new List<Assembly>()
{
typeof(CachedImage).GetTypeInfo().Assembly,
typeof(CachedImageRenderer).GetTypeInfo().Assembly
};
Xamarin.Forms.Forms.Init(e, assembliesToInclude);
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
// Ensure the current window is active
Window.Current.Activate();
if (session == null)
{
// prevent the app from stopping when minimized
session = new ExtendedExecutionSession();
session.Reason = ExtendedExecutionReason.Unspecified;
session.Revoked += (s, a) => { };
var result = await session.RequestExtensionAsync();
if (result == ExtendedExecutionResult.Denied)
System.Diagnostics.Debug.WriteLine("EXTENDED EXECUTION DENIED");
}
}
The problem is that you are trying to cast the IActivatedEventArgs to LaunchActivatedEventArgs, but when startup activation happens, the type is actually StartupTaskActivatedEventArgs.
Luckily, you actually need the e parameter only for Xamarin.Forms.Forms.Init which actually accepts IActivatedEventArgs, so you can just change the parameter of InitializeApp to be IActivatedEventArgs and remove the cast to LaunchActivatedEventArgs in OnActivated.

(UWP) Hardware Back Press work correctly in mobile but error with PC

In my UWP app when i click on mobile back button app get close, so add this code in app.xaml.cs
private async void HardwareButtons_BackPressed(object sender, BackPressedEventArgs e)
{
e.Handled = true;
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack && rootFrame != null)
{
rootFrame.GoBack();
}
else
{
var msg = new MessageDialog("Confirm Close! \nOr Press Refresh Button to Go Back");
var okBtn = new UICommand("OK");
var cancelBtn = new UICommand("Cancel");
msg.Commands.Add(okBtn);
msg.Commands.Add(cancelBtn);
IUICommand result = await msg.ShowAsync();
if (result != null && result.Label == "OK")
{
Application.Current.Exit();
}
}
}
and
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
/* Because of this line my app work on mobile great but when
when i debug on pc it through exception "show in image" */
HardwareButtons.BackPressed += HardwareButtons_BackPressed;
}
After Done all this code when i debug app on phone, app successfully run -
Mobile Debuging:
But when debug in pc with same code, it show this error- PC Debuging:
when i remove HardwareButtons.BackPressed += HardwareButtons_BackPressed; then issue with pc debugging resolved but in mobile debuging back button again is not work.
The reason is that HardwareButtons API is not the universal solution for handling the back button. This API is available only in the Mobile extension SDK and trying to invoke it on other SKU will cause this exception, because the type is not available.
To enable the same functionality on all systems, you will need to use the new universal back button event:
SystemNavigationManager.GetForCurrentView().BackRequested += BackButtonHandler;
This will work the same on phone, PC, tablets,Xbox One, Surface Hub and HoloLens.
On PC this button is not shown by default, so you have to display it manually or create your own. To show the Back button in window's title bar, use:
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
AppViewBackButtonVisibility.Visible;
It is recommended that you hide this button once Frame.CanGoBack is false, because in that case the button is no longer useful. You should do this after each navigation of the frame. Best place to do this is when setting up the root frame in App.xaml.cs:
Frame rootFrame = Window.Current.Content as Frame;
rootFrame.Navigated += UpdateAppViewBackButton;
Now the handler could look like this:
private void UpdateAppViewBackButton( object sender, NavigationEventArgs e )
{
Frame frame = (Frame) sender;
var systemNavigationManager = SystemNavigationManager.GetForCurrentView();
systemNavigationManager.AppViewBackButtonVisibility =
frame.CanGoBack ? AppViewBackButtonVisibility.Visible :
AppViewBackButtonVisibility.Collapsed;
}
On Application close
I have also noticed that you are using Application.Current.Exit(); to exit the app. This is however not recommended. Once the user chooses OK in the dialog, you should rather set the e.Handled = false and let the system handle the app close manually. This will ensure the app suspension will run as expected and the app will stay in memory if the system has enough resources and will then launch faster again. Application.Current.Exit() kills the application and it is not recommended for UWP apps.
One thing to remember is that on Desktop, there is currently no way to catch the user clicking the close button in the app's title bar, so your confirmation dialog will not display in that case unfortunately.

How to set start page in windows phone 8 app programmatically?

I want to set a start page in my windows phone 8 app programmatically after checking some data in config. Which event I can use to do the same?
Thanx in advance.
I used Application_Launching for same task. Something like this:
private void Application_Launching(object sender, LaunchingEventArgs e)
{
RootFrame.Navigated += RootFrame_Navigated;
var logined = Singleton.Instance.User.Load();
var navigatingUri = logined ? "/View/PageMainPanorama.xaml" : "/View/Account/PageLoginRegister.xaml";
((App)Current).RootFrame.Navigate(new Uri(navigatingUri, UriKind.Relative));
}
The first step is to remove the default page that us set by default in the manifest file (WMAppManifest.xml) in apps created from the standard templates.
Simply remove NavigationPage="MainPage.xaml" from the code below.
<Tasks>
<DefaultTask Name="_default" NavigationPage="MainPage.xaml" />
</Tasks>
The start page is specified in InitializePhoneApplication() by calling RootFrame.Navigate() (in App.xaml.cs) .Like example below
private void InitializePhoneApplication()
{
if (phoneApplicationInitialized)
return;
// Create the frame but don't set it as RootVisual yet; this allows the splash
// screen to remain active until the application is ready to render.
RootFrame = new PhoneApplicationFrame();
RootFrame.Navigated += CompleteInitializePhoneApplication;
// Handle navigation failures
RootFrame.NavigationFailed += RootFrame_NavigationFailed;
// Handle reset requests for clearing the backstack
RootFrame.Navigated += CheckForResetNavigation;
// Ensure we don't initialize again
phoneApplicationInitialized = true;
Uri uri;
if (IsolatedStorageSettings.ApplicationSettings.Contains("islogin"))
{
if (!(Convert.ToString(IsolatedStorageSettings.ApplicationSettings["islogin"]).ToLower() == "yes"))
{
RootFrame.Navigate(new Uri("/LoginScreen.xaml", UriKind.RelativeOrAbsolute));
}
else
{
RootFrame.Navigate(new Uri("/HomeScreen.xaml", UriKind.RelativeOrAbsolute));
}
}
else
{
RootFrame.Navigate(new Uri("/LoginScreen.xaml", UriKind.RelativeOrAbsolute));
}
}
Here you can find a blog entry that describes the dynamic setting of a start page.
http://blogs.msdn.com/b/ptorr/archive/2010/08/28/redirecting-an-initial-navigation.aspx?wa=wsignin1.0

Change App language at RunTime on-the-fly

I'm currently developing a metro app in which the user can change current language at runtime and all the custom controls that are loaded must update their text regarding to the new language. Problem is that when I change the language using the following code, the app language changes but it will only update text when I restart my app because the pages and controls that are already rendered are cached.
LocalizationManager.UICulture = new System.Globalization.CultureInfo((string)((ComboBoxItem)e.AddedItems[0]).Tag);
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = ((ComboBoxItem)e.AddedItems[0]).Tag as String;
What should I do to force updating text of all custom controls at runtime without restarting my app?
Use this:
var NewLanguage = (string)((ComboBoxItem)e.AddedItems[0]).Tag;
Windows.Globalization.ApplicationLanguages.PrimaryLanguageOverride = NewLanguage;
Windows.ApplicationModel.Resources.Core.ResourceContext.GetForViewIndependentUse().Reset();
//Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().Reset();
Windows.ApplicationModel.Resources.Core.ResourceManager.Current.DefaultContext.Reset();
and then reload your Page, using Navigate method:
if (Frame != null)
Frame.Navigate(typeof(MyPage));
In order to respond right away, you would need to reset the context of the resource manager.
For Windows 8.1:
var resourceContext = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView();
resourceContext.Reset();
You will still need to force your page to redraw itself and thus re-request the resources to get the changes to take place. For Windows 8, you can see https://timheuer.com/blog/archive/2013/03/26/howto-refresh-languages-winrt-xaml-windows-store.aspx
You can change the app's language at runtime with the help of this source code. I took help from this and manipulated my app's language settings page as follows:
In languageSettings.xaml.cs:
public partial class LanguageSettings : PhoneApplicationPage
{
public LanguageSettings()
{
InitializeComponent();
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (ChangeLanguageCombo.Items.Count == 0)
{ ChangeLanguageCombo.Items.Add(LocalizationManager.SupportedLanguages.En);
ChangeLanguageCombo.Items.Add(LocalizationManager.SupportedLanguages.Bn);
}
SelectChoice();
}
private void ButtonSaveLang_OnClick(object sender, RoutedEventArgs e)
{
//Store the Messagebox result in result variable
MessageBoxResult result = MessageBox.Show("App language will be changed. Do you want to continue?", "Apply Changes", MessageBoxButton.OKCancel);
//check if user clicked on ok
if (result == MessageBoxResult.OK)
{
var languageComboBox = ChangeLanguageCombo.SelectedItem;
LocalizationManager.ChangeAppLanguage(languageComboBox.ToString());
//Application.Current.Terminate(); I am commenting out because I don't neede to restart my app anymore.
}
else
{
SelectChoice();
}
}
private void SelectChoice()
{
//Select the saved language
string lang = LocalizationManager.GetCurrentAppLang();
if(lang == "bn-BD")
ChangeLanguageCombo.SelectedItem = ChangeLanguageCombo.Items[1];
else
{
ChangeLanguageCombo.SelectedItem = ChangeLanguageCombo.Items[0];
}
}
}
***Note: Before understanding what I did on LanguageSettings page's code behind, you must implement the codes from the link as stated earlier. And also it may be noted that I am working on windows phone 8

Placing a link in windows 8 metro style app

How can I link my web address www.facebook.com to my hyperlink button.and that should load in my app page.
You can only load a web page inside a WebView control. Put it somewhere on your page first:
<WebView x:Name="MyWebView" />
In the click event handler of your Hyperlink load the page into this WebView:
private void Hyperlink_OnClick(object sender, RoutedEventArgs e)
{
MyWebView.Navigate(new Uri("http://www.facebook.com"));
}
Process.Start("http://facebook.com"); that will load the default browser at facebook.com is this what you require ?
how about the launcher class ? You can use the Launcher class to launch a document in the default handler, i.e load a website with the default browser, from what i understand you cant just create a process.
async void DefaultLaunch()
{
// Path to the file in the app package to launch
string imageFile = #"images\test.png";
var file = wait Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(imageFile);
if (file != null)
{
// Launch the retrieved file
var success = await Windows.System.Launcher.LaunchFileAsync(file);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
else
{
// Could not find file
}
}

Categories

Resources