C# WIndows Phone 8.1 not loading background - c#

I'm trying to set one image for all my pages in the solution. I'm working in the app.xaml.cs file and I'm trying to adjust the rootFrame like this :
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
if (System.Diagnostics.Debugger.IsAttached)
{
DebugSettings.EnableFrameRateCounter = true;
}
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)
{
rootFrame = new Frame //THATS WHAT I ADDED
{
Background = new ImageBrush()
{
ImageSource = new BitmapImage(new Uri("ms-appx:/Assets/wood_background.jpg", UriKind.Absolute)),
Stretch = Stretch.None,
AlignmentX = AlignmentX.Center,
AlignmentY = AlignmentY.Center
}
};
// Create a Frame to act as the navigation context and navigate to the first page
//rootFrame = new Frame {CacheSize = 1};
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
// Removes the turnstile navigation for startup.
if (rootFrame.ContentTransitions != null)
{
transitions = new TransitionCollection();
foreach (var c in rootFrame.ContentTransitions)
{
transitions.Add(c);
}
}
rootFrame.ContentTransitions = null;
rootFrame.Navigated += RootFrame_FirstNavigated;
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation
// parameter
if (!rootFrame.Navigate(typeof(MainPage), e.Arguments))
{
throw new Exception("Failed to create initial page");
}
}
// Ensure the current window is active
Window.Current.Activate();
}
however the initialization of the rootFrame background doesn't seem to change something at all. My image is located in documents folder of the project under Windows Phone\Assets.

Related

Passing and receiving variables through Process.start parameter (Winform to UWP)

My UWP program is registered as protocol and it is made to call through button of Winform program.
I want to receive the value from UWP by passing the variable value in the Winform program, but I'm not sure how to receive the passed argument in UWP(XAML).
winform
ProcessStartInfo startinfo = new ProcessStartInfo();
startinfo.FileName = "safety:";
startinfo.Arguments = LOGIN.userinfo.user_id;
Process.Start(startinfo);
UWP(App.Xaml.cs)
protected override void OnActivated(IActivatedEventArgs args)
{
//Initialize(args);
if (args.Kind == ActivationKind.Protocol)
{
ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
// Always navigate for a protocol launch
rootFrame.Navigate(typeof(MainPage), eventArgs.Uri.AbsoluteUri);
// Ensure the current window is active
Window.Current.Activate();
}
}
Only once. when i click a button in Winform
You could use add the data that you want to app into the Launcher.LaunchUriAsync(Uri, LauncherOptions, ValueSet) Method. Then you could get the data from the ProtocolActivatedEventArgs of the OnActivated event.
I have implemented a sample demo based on your code and you could refer to the following code:
UWP app:
protected override void OnActivated(IActivatedEventArgs args)
{
if (args.Kind == ActivationKind.Protocol)
{
ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
//get the data from Winforms apps
ValueSet data = eventArgs.Data;
var d = data["token1"];
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
Window.Current.Content = rootFrame;
}
// pass the data to the MainPage
rootFrame.Navigate(typeof(MainPage), d);
Window.Current.Activate();
}
}
In the MainPage of the UWP app:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
var str = e.Parameter.ToString();
}
When you call the LaunchUriAsync, change it like the following:
// Launch the URI
var uri = new Uri("alsdk:");
// create data.
ValueSet v = new ValueSet();
v.Add("token1", "12");
// create LauncherOptions
var options = new Windows.System.LauncherOptions();
options.TargetApplicationPackageFamilyName = "PackageFamilyName of Your UWP project";
var success = await Windows.System.Launcher.LaunchUriAsync(uri, options, v);
I solved this problem another way like this
winform
Process.Start("safetytest:"+LOGIN.userinfo.user_id);
UWP(App.Xaml.cs)
protected override void OnActivated(IActivatedEventArgs args)
{
ThemeHelper.Initialize();
Initialize(args);
if (args.Kind == ActivationKind.Protocol)
{
ProtocolActivatedEventArgs eventArgs = args as ProtocolActivatedEventArgs;
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
rootFrame.Navigate(typeof(MainPage), eventArgs.Uri.ToString());//this
Window.Current.Activate();
}
}
UWP Main
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
SafetyApp.user_info.user_id = e.Parameter.ToString().Substring(11);
var dialog = new MessageDialog(String.Format(user_info.user_id));
await dialog.ShowAsync();
}

UWP create new window for each file opened

I'm trying to make an app open a window for each file.
-- Code ---
App.cs:
protected async override void OnFileActivated(FileActivatedEventArgs Args)
{
//Opens Main Page
base.OnFileActivated(Args);
var RF = new Frame();
var MW = new MainPage();
AppWindow appWindow = await AppWindow.TryCreateAsync();
var TB = appWindow.TitleBar;
RF.Navigate(typeof(MainPage), Args);
ElementCompositionPreview.SetAppWindowContent(appWindow, RF);
appWindow.Equals(MW);
Window.Current.Equals(MW);
await appWindow.TryShowAsync();
TB.ButtonHoverBackgroundColor = Colors.White;
TB.ButtonHoverForegroundColor = Colors.Black;
TB.ButtonBackgroundColor = Colors.Transparent;
TB.ButtonPressedBackgroundColor = Colors.WhiteSmoke;
TB.ButtonPressedForegroundColor = Colors.Black;
TB.ButtonInactiveBackgroundColor = Colors.Transparent;
TB.ButtonInactiveForegroundColor = Color.FromArgb(1, 3, 165, 252);
TB.ExtendsContentIntoTitleBar = true;
Window.Current.Activate();
}
MainPage.cs:
protected override async void OnNavigatedTo(NavigationEventArgs EvArgs)
{
//File opened arguments
base.OnNavigatedTo(EvArgs);
var Args = EvArgs.Parameter as IActivatedEventArgs;
var FArgs = Args as FileActivatedEventArgs;
string Value = GetText(REB);
string SecValue = GetText(RTB);
if (Args != null)
{
//Check if the app is opened by file
if (Args.Kind == ActivationKind.File)
{
//Set file content
TXTFile = FArgs.Files[0] as StorageFile;
if (Value == "")
{
var Str = await TXTFile.OpenReadAsync();
ContentDialog ED2 = FileSaveDialog;
ED2.PrimaryButtonClick += ED2_PrimaryButtonClick;
void ED2_PrimaryButtonClick(ContentDialog Sender, ContentDialogButtonClickEventArgs DialogEvArgs)
{
//Save the file if it isn't saved
Save();
}
ED2.SecondaryButtonClick += ED2_SecondaryButtonClick;
void ED2_SecondaryButtonClick(ContentDialog Sender, ContentDialogButtonClickEventArgs DialogEvArgs)
{
//Don't save the file
//Set document content
REB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
RTB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
Str.Dispose();
}
ED2.CloseButtonClick += ED2_CloseButtonClick;
void ED2_CloseButtonClick(ContentDialog Sender, ContentDialogButtonClickEventArgs DialogEvArgs)
{
//Cancel the action
}
await ED2.ShowAsync();
Str.Dispose();
}
else
{
//Set document content
var Str = await TXTFile.OpenReadAsync();
REB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
RTB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
Str.Dispose();
}
}
}
else
{
//If there are no arguments, the file, and the RichEditBox should both remain empty
}
}
public string GetText(RichEditBox RichEditor)
{
RichEditor.Document.GetText(TextGetOptions.FormatRtf, out string Text);
var Range = RichEditor.Document.GetRange(0, Text.Length);
Range.GetText(TextGetOptions.FormatRtf, out string Value);
return Value;
}
Note:
the GetText method used is equivalent to RichEditBox.Document.GetText(TextGetOptions.FormatRtf, out string Value);
REB is the main workspace for the user to type in
RTB is the box that is compared with REB to see if the contents are saved or not (if the contents are saved, the GetText method should return their values equal)
Expected behavior:
If the app has a window active with text, the app should open a file on double click in a secondary window. Else, if the text is equal to "", the app should replace it with whatever is in the file.
Actual behavior:
The app overrides the text, crashes, makes windows randomly, or creates black windows that can only be killed with Task Manager or Visual Studio
I'm not sure what is the file type that you are using so I didn't check the text part. But I have to say that the way you are creating a new window is not correct. If you want to open a new window every time when you open a new file, you don't have to call Window.Current.Activate(); every time. I've made a simple demo that you could check.
In App.xaml.cs:
protected async override void OnFileActivated(FileActivatedEventArgs args)
{
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();
// Place the frame in the current Window
Window.Current.Content = rootFrame;
rootFrame.Navigate(typeof(MainPage), args.Files);
Window.Current.Activate();
}
else
{
AppWindow appWindow = await AppWindow.TryCreateAsync();
Frame appWindowContentFrame = new Frame();
appWindowContentFrame.Navigate(typeof(MainPage),args.Files);
ElementCompositionPreview.SetAppWindowContent(appWindow, appWindowContentFrame);
await appWindow.TryShowAsync();
}
}
When you launch the app for the first time, you should go through the normal launch process. When the app is launched more than onetime, then you could create a new window with AppWindow.
In MainPage.cs
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// this is the file you need
var d = e.Parameter;
}
You could try this code first to make sure that your window is created and shown correctly.

Navigating from App.xaml.cs when receiving push notification

Hi i want my app to navigate to a page when i receive a push toast notification. My code is as follows:-
ParsePush.ToastNotificationReceived += OnPushNotification;
This is to handle the event of push
private async void OnPushNotification(object sender, Windows.Networking.PushNotifications.PushNotificationReceivedEventArgs e)
{
var AdFrame = Window.Current.Content as Frame;
var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
if (localSettings.Values.ContainsKey("Suspended"))
{
String value = localSettings.Values["Suspended"].ToString();
if (value != null)
{
if (value == "false")
{
AdFrame.Navigate(typeof(Ad));
}
}
}
}
I get a Null Reference Error at var AdFrame = Window.Current.Content as Frame;
I have added this code in App.xaml.cs .I just want to navigate to the Ad Page from current page , whatever page maybe active. I am pretty new to windows , any help will be appreciated.
You will need to display a toast notification instead:
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(
ToastTemplateType.ToastImageAndText02);
XmlNodeList stringElements = toastXml.GetElementsByTagName("text");
stringElements.Item(0).AppendChild(toastXml.CreateTextNode("Hello world!"));
IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
XmlAttribute launchAttribute = toastXml.CreateAttribute("launch");
launchAttribute.Value = "pass data here"; // TODO: pass data here
toastNode.Attributes.SetNamedItem(launchAttribute);
ToastNotification toast = new ToastNotification(toastXml);
ToastNotificationManager.CreateToastNotifier().Show(toast);
When user clicks on the toast notification, you can handle the App launch event and then read the data.
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
// ...
MainPage page = rootFrame.Content as MainPage;
page.ParseData(e.Arguments);
}

Navigating between pages in windows 8.1

I need to navigate to specific page according to:
Frame rootFrame = Window.Current.Content as Frame;
rootFrame.Navigate(typeof(rootFrame.Name));
but rootFrame.Name = page name that is needed is a string not frame
Any Help!!
Try:
public void NavigateToPage<T>()
{
var type = typeof(T);
var testvalue = (type.FullName.Substring(type.FullName.IndexOf('.')).Replace('.', '/')) + ".xaml";
RootFrame.Navigate(new Uri(testvalue, UriKind.Relative));
}

File Associations in a Windows Store App, what am I doing wrong?

I followed the msdn tutorial and another tutorial, but I don't know what I'm doing wrong. In app.xaml.cs, I have the code
protected override void OnFileActivated(FileActivatedEventArgs args)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
}
var p = rootFrame.Content as MainPage;
p.FileEvent = args;
Window.Current.Activate();
}
In MainPage.xaml.cs I have the code
private FileActivatedEventArgs _fileEventArgs = null;
public FileActivatedEventArgs FileEvent
{
get { return _fileEventArgs; }
set { _fileEventArgs = value; }
}
and
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
//get the args
if (FileEvent != null && FileEvent.Files.Count > 0)
{
titleText.Text = FileEvent.Files[0].Path.ToString();
}
}
which is called in the MainPage constructor after this.InitializeComponent().
I'm not sure how to debug it. When I double click on an mp3 file that is associated with the app, the app opens but does not start, and the file has the waiting pointer icon until I close the app, then I receive an error that says The App didn't start in the required time. If the app is already open when I click on the file, nothing happens, and when I close the app it says The Remote procedure call failed.
I found the answer, I had put the entry point to MainPage.xaml, but changing it to App.xaml.cs fixed it so it actually called OnFileActivated(). I also changed the OnFileActivated code to
protected override void OnFileActivated(FileActivatedEventArgs args)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
if (!rootFrame.Navigate(typeof(MainPage)))
{
throw new Exception("Failed to create initial page");
}
}
var p = rootFrame.Content as MainPage;
if (p != null) p.FileEvent = args;
p.MainPage_Loaded(null, null);
Window.Current.Activate();
}
calling the public method p.MainPage_Loaded() in MainPage.xaml.cs from App.xaml.css was the final touch that allowed me to use the method without creating a new frame if the app was already open.

Categories

Resources