I'm trying to make a tab appear for every file opened via File Explorer.
Expectations: upon double click on the file, it should open up a new tab for that file
Reality: every time I open a file, the frame gets overwritten.
MainPage - contains tabs
TabbedMainPage - the workspace
App.cs:
protected override void OnFileActivated(FileActivatedEventArgs Args)
{
base.OnFileActivated(Args);
Frame RF = Window.Current.Content as Frame;
if (RF != null)
{
var Y = new FrameNavigationOptions();
Y.IsNavigationStackEnabled = false;
RF.NavigateToType(typeof(MainPage), Args, Y);
}
else
{
RF = new Frame();
Window.Current.Content = RF;
RF.Navigate(typeof(MainPage), Args);
Window.Current.Activate();
}
}
MainPage.cs:
protected override void OnNavigatedTo(NavigationEventArgs EvArgs)
{
//Catch file
base.OnNavigatedTo(EvArgs);
var Args = EvArgs.Parameter as IActivatedEventArgs;
var FArgs = Args as FileActivatedEventArgs;
if (Args != null && Args.Kind == ActivationKind.File)
{
//Write file properties
TabViewItem NewTabItem = new TabViewItem();
NewTabItem.Header = "New Tab";
NewTabItem.IconSource = new Microsoft.UI.Xaml.Controls.SymbolIconSource() { Symbol = Symbol.Document };
Frame RF = new Frame();
RF.Navigate(typeof(TabbedMainPage), Args);
NewTabItem.Content = RF;
TabbedView.TabItems.Add(NewTabItem);
TabbedView.UpdateLayout();
}
else { }
}
TabbedMainPage.cs:
protected override async void OnNavigatedTo(NavigationEventArgs EvArgs)
{
//Catch file
base.OnNavigatedTo(EvArgs);
var Args = EvArgs.Parameter as IActivatedEventArgs;
var FArgs = Args as FileActivatedEventArgs;
if (Args != null && Args.Kind == ActivationKind.File)
{
//Write file properties
TXTFile = FArgs.Files[0] as StorageFile;
var Str = await TXTFile.OpenReadAsync();
//Read file
REB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
RTB.Document.LoadFromStream(TextSetOptions.FormatRtf, Str);
Str.Dispose();
HomePage.Visibility = Visibility.Collapsed;
CheckForSaving();
}
else { }
}
Related
I have several DialogFragement's in my app that I need to transition to Android.Support.V4.App.DialogFragment so my app is compatible with API 29 (Q). I began by converting my "Change Password" dialog fragment code to this:
class ChangePassword : Android.Support.V4.App.DialogFragment
{
public event DialogEventHandler Dismissed;
public string selection = "";
private int error = 0;
public User MyUser;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView(inflater, container, savedInstanceState);
View view = inflater.Inflate(Resource.Layout.ChangePassword, container, false);
Button ok = view.FindViewById<Button>(Resource.Id.button_ok);
EditText currentPassword = view.FindViewById<EditText>(Resource.Id.currentPassword);
EditText newPassword1 = view.FindViewById<EditText>(Resource.Id.newPassword1);
EditText newPassword2 = view.FindViewById<EditText>(Resource.Id.newPassword2);
ok.Click += (sender, args) =>
{
if (currentPassword.Text != "" && (newPassword1.Text.ToUpper () == newPassword2.Text.ToUpper()) && (newPassword1.Text != "" || newPassword2.Text != ""))
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
OMLDataInterfaceWeb.OMLDataInterface datainterface = new OMLDataInterfaceWeb.OMLDataInterface();
try
{
datainterface.ChangeUserPassword(MyUser.Username, currentPassword.Text, newPassword1.Text);
}
catch (Exception e)
{
error = 1;
Utils.showMessage(e.Message, "Error");
}
if (error == 0)
{
selection = newPassword2.Text;
if (null != Dismissed)
Dismissed(this, new DialogEventArgs { Selection = selection });
}
}
else
{
if (currentPassword.Text == "")
{
// Android.Content.Context context = new AppContext() ;
Utils.showMessage("Enter the current password.","ERROR");
}
else
{
if (newPassword1.Text == "")
{
Utils.showMessage("The first new password field is blank.", "ERROR");
} else if (newPassword2.Text == "")
{
Utils.showMessage("Please re-enter the new password.", "ERROR");
} else if (newPassword1.Text.ToUpper() != newPassword2.Text.ToUpper())
{
Utils.showMessage("The passwords do not match.", "ERROR");
}
}
}
};
return view;
}
public override void OnResume()
{
int width = 900;
int height = 900;
Dialog.Window.SetLayout(width, height);
base.OnResume();
}
}
Note that I'm using Android.Support.V4.App.DialogFragment as opposed to the Android.App.DialogFragment.
I call this from another activity with a button click, that code is:
btnChangePassword.Click += (sender, e) =>
{
Android.Support.V4.App.FragmentTransaction transcation = FragmentManager; //FragmentManager; // FragmentManager.BeginTransaction();
ChangePassword changePassword = new ChangePassword();
changePassword.MyUser = MyUser;
changePassword.Show(transcation, "Dialog");
changePassword.Dismissed += (s, a) => {
/* do something with e.Selection here */
if (a.Selection.ToUpper() != "")
{
ChangePassword _exportFragment = (ChangePassword)FragmentManager.FindFragmentByTag("Dialog");
if (_exportFragment != null)
{
_exportFragment.Dismiss();
}
changedPassword = true;
thePassword = a.Selection;
}
else
{
Toast.MakeText(this, "Enter new password.", ToastLength.Long).Show();
}
};
};
I'm getting two errors in the button click code, the first is Cannot implicitly convert type 'Android.App.FragmentManager' to 'Android.Support.V4.App.FragmentTransaction which occurs on this line of code Android.Support.V4.App.FragmentTransaction transcation = FragmentManager;, assuming that I also had to qualify FragmentManager with Android.Support.V4.App., I changed the code to read Android.Support.V4.App.FragmentTransaction transcation = Android.Support.V4.App.FragmentManager;, this generated the error 'FragmentManager' is a type, which is not valid in the given context, the other error Im getting is Cannot convert type 'Android.App.Fragment' to 'MyAndroidApp.ChangePassword' which occurs on the line ChangePassword _exportFragment = (ChangePassword)FragmentManager.FindFragmentByTag("Dialog");. I've searched all ove for an answer and nothing I've tried has resolved this. What am I missing?
I was able to figure it out. The new button click code is:
btnChangePassword.Click += (sender, e) =>
{
Android.Support.V4.App.FragmentTransaction transcation = SupportFragmentManager.BeginTransaction();
ChangePassword changePassword = new ChangePassword();
changePassword.MyUser = MyUser;
changePassword.Show(transcation, "Dialog");
changePassword.Dismissed += (s, a) => {
/* do something with e.Selection here */
if (a.Selection.ToUpper() != "")
{
ChangePassword _exportFragment = (ChangePassword)SupportFragmentManager.FindFragmentByTag("Dialog");
if (_exportFragment != null)
{
_exportFragment.Dismiss();
}
changedPassword = true;
thePassword = a.Selection;
}
else
{
Toast.MakeText(this, "Enter new password.", ToastLength.Long).Show();
}
};
When closing Form containing a WebBrowser control with a Pdf document open in the webbrowser, the form takes some 10 seconds to close. I tracked the issue down to Dispose method of the webbrowser.
private void advBandedGridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
{
if (advBandedGridView1.GetFocusedDataRow() != null)
{
string wordno = advBandedGridView1.GetFocusedDataRow()["wordno"].ToString();
string itemcd = advBandedGridView1.GetFocusedDataRow()["itemcd"].ToString();
for (int i = 0; i < _caseCount; i++)
{
ButtonColoring(wordno, _seqkindCode[i]);
}
LoadPDF(itemcd);
gridControl2.DataSource = null;
gridControl2.RefreshDataSource();
}
}
Control Event
private void LoadPDF(string itemcd)
{
try
{
ReturnPacket rp;
rp = new Q3i.POP.BIZ.Common.CommonCode().SelectCommonCodeFull("603", "kind3 = 'EYE'", false);
if (rp.DataTables.Count > 0 && rp.DataTables[0].Rows.Count == 0)
{
rp = new Q3i.POP.BIZ.Common.CommonCode().SelectCommonCodeFull("603", "kind3 = '1'", false);
}
if (rp.DataTables[0].Rows.Count > 0)
{
string dockind = string.Empty;
dockind = rp.DataTables[0].Rows[0]["code"].ToString();
ParameterCollection paramCol = new ParameterCollection();
paramCol.Add("p_itemcd", itemcd);
paramCol.Add("p_dockind", dockind);
PdfFileInfo temp_fileInfo = biz.SelectInspectionStandards(paramCol);
if (temp_fileInfo != null)
{
if (_fileInfo != null && temp_fileInfo.FileNm == _fileInfo.FileNm)
{
WebBrowserPdf.Visible = true;
return;
}
_fileInfo = null;
_fileInfo = temp_fileInfo;
PDF_FILE_PATH = FilePath + _fileInfo.FileNm;
DirectoryInfo di = new DirectoryInfo(FilePath);
if (di.Exists == false)
{
di.Create();
}
if (!File.Exists(PDF_FILE_PATH))
File.WriteAllBytes(PDF_FILE_PATH, _fileInfo.FileData);
if (!PDF_FILES.Contains(PDF_FILE_PATH))
{
PDF_FILES.Add(PDF_FILE_PATH);
}
WebBrowserPdf.Navigate(PDF_FILE_PATH + "?#zoom=" + _zoomFactor + "%", false);
WebBrowserPdf.Visible = true;
simpleButtonOpenPOPUP.Enabled = true;
}
else
{
WebBrowserPdf.Visible = false;
simpleButtonOpenPOPUP.Enabled = false;
}
}
}
catch (Exception ex)
{
UCXtraMsgBox.ShowDialog(ex.Message, "m0146", Q3i.Common.Enums.MsgBoxButton.OK, Q3i.Common.Enums.MsgBoxIcon.Alert, true);
}
}
it is Load Method
private void w_pcmu081_FormClosing(object sender, FormClosingEventArgs e)
{
try
{
WebBrowserPdf.Dispose();
Process[] Pro = Process.GetProcessesByName("osk");
if (Pro.GetLength(0) > 0)
Pro[0].Kill();
}
catch(Exception ex)
{
UCXtraMsgBox.ShowDialog(ex.Message, "m0146", Q3i.Common.Enums.MsgBoxButton.OK, Q3i.Common.Enums.MsgBoxIcon.Info, true, null, true);
}
}
Closing
The same situation happened to me.
Adobe has done something wrong in the latest version of Acrobat Reader DC (15.023.20056).
If you uncheck option Enable Protected Mode at startup in Edit -> Preferences -> Security (Enhanced), everything will be back to normal.
On my case it is not a solution.
More info here: https://forums.adobe.com/thread/2267688
Cannot Implicitly convert type "String" to "Windows.Security.Credentials.PasswordCredential"
After about 4 hours of searching I cannot figure out this error. I am using the Windows 10 IOT Core on a RPI 3. My program is pretty basic, however I can not convert the datatype within the code to resolve the error.
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using Windows.Devices.WiFi;
using Windows.Networking.Connectivity;
using Windows.Security.Credentials;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
namespace WiFiConnect
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class WiFiConnect_Scenario : Page
{
MainPage rootPage;
private WiFiAdapter firstAdapter;
public ObservableCollection<WiFiNetworkDisplay> ResultCollection
{
get;
private set;
}
public WiFiConnect_Scenario()
{
this.InitializeComponent();
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
ResultCollection = new ObservableCollection<WiFiNetworkDisplay>();
rootPage = MainPage.Current;
// RequestAccessAsync must have been called at least once by the app before using the API
// Calling it multiple times is fine but not necessary
// RequestAccessAsync must be called from the UI thread
var access = await WiFiAdapter.RequestAccessAsync();
if (access != WiFiAccessStatus.Allowed)
{
rootPage.NotifyUser("Access denied", NotifyType.ErrorMessage);
}
else
{
DataContext = this;
var result = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(WiFiAdapter.GetDevice Selector());
if (result.Count >= 1)
{
firstAdapter = await WiFiAdapter.FromIdAsync(result[0].Id);
var button = new Button();
button.Content = string.Format("Scan Available Wifi Networks");
button.Click += Button_Click;
Buttons.Children.Add(button);
}
else
{
rootPage.NotifyUser("No WiFi Adapters detected on this machine.", NotifyType.ErrorMessage);
}
}
}
private async void Button_Click(object sender, RoutedEventArgs e)
{
await firstAdapter.ScanAsync();
ConnectionBar.Visibility = Visibility.Collapsed;
DisplayNetworkReport(firstAdapter.NetworkReport);
}
private void DisplayNetworkReport(WiFiNetworkReport report)
{
rootPage.NotifyUser(string.Format("Network Report Timestamp: {0}", report.Timestamp), NotifyType.StatusMessage);
ResultCollection.Clear();
foreach (var network in report.AvailableNetworks)
{
ResultCollection.Add(new WiFiNetworkDisplay(network, firstAdapter));
}
}
private void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null)
{
return;
}
// Show the connection bar
ConnectionBar.Visibility = Visibility.Visible;
// Only show the password box if needed
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
NetworkKeyInfo.Visibility = Visibility.Collapsed;
}
else
{
NetworkKeyInfo.Visibility = Visibility.Visible;
}
}
private async void ConnectButton_Click(object sender, RoutedEventArgs e)
{
var selectedNetwork = ResultsListView.SelectedItem as WiFiNetworkDisplay;
if (selectedNetwork == null || firstAdapter == null)
{
rootPage.NotifyUser("Network not selcted", NotifyType.ErrorMessage);
return;
}
WiFiReconnectionKind reconnectionKind = WiFiReconnectionKind.Manual;
if (IsAutomaticReconnection.IsChecked.HasValue && IsAutomaticReconnection.IsChecked == true)
{
reconnectionKind = WiFiReconnectionKind.Automatic;
}
WiFiConnectionResult result;
if (selectedNetwork.AvailableNetwork.SecuritySettings.NetworkAuthenticationType == Windows.Networking.Connectivity.NetworkAuthenticationType.Open80211 &&
selectedNetwork.AvailableNetwork.SecuritySettings.NetworkEncryptionType == NetworkEncryptionType.None)
{
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind);
}
else
{
FileStream file = new FileStream("final-wordlist.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(file);
sr.ReadLine();
var textLines = File.ReadAllLines("final-wordlist.txt");
foreach (var line in textLines)
{
string[] dataArray = line.Split(' ');
foreach (var item in dataArray)
{
PasswordCredential credential = line;
//string credential = line.ToString();
result = await firstAdapter.ConnectAsync(selectedNetwork.AvailableNetwork, reconnectionKind, credential);
}
}
// Only the password potion of the credential need to be supplied
}
if (result.ConnectionStatus == WiFiConnectionStatus.Success)
{
rootPage.NotifyUser(string.Format("Successfully connected to {0}.", selectedNetwork.Ssid), NotifyType.StatusMessage);
// refresh the webpage
webViewGrid.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
refreshBrowserButton.Visibility = Visibility.Visible;
}
else
{
rootPage.NotifyUser(string.Format("Could not connect to {0}. Error: {1}", selectedNetwork.Ssid, result.ConnectionStatus), NotifyType.ErrorMessage);
}
// Since a connection attempt was made, update the connectivity level displayed for each
foreach (var network in ResultCollection)
{
network.UpdateConnectivityLevel();
}
}
private void Browser_Toggle_Click(object sender, RoutedEventArgs e)
{
if (webViewGrid.Visibility == Visibility.Visible)
{
webViewGrid.Visibility = Visibility.Collapsed;
refreshBrowserButton.Visibility = Visibility.Collapsed;
toggleBrowserButton.Content = "Show Browser Control";
}
else
{
webViewGrid.Visibility = Visibility.Visible;
refreshBrowserButton.Visibility = Visibility.Visible;
toggleBrowserButton.Content = "Hide Browser Control";
}
}
private void Browser_Refresh(object sender, RoutedEventArgs e)
{
webView.Refresh();
}
}
}
This worked for me. The problem was it was it need more than one var to fill it.
var credential = new PasswordCredential("Module", "Username", "Password");
Try this:
PasswordCredential credential = null;
if (!string.IsNullOrEmpty(line))
{
credential = new PasswordCredential()
{
Password = line
};
}
I have userControl(wpf)
public WebBrowserControl()
{
InitializeComponent();
_Browser = new WebBrowser();
_pipeClient = new NamedPipeClient<WebMessage>("TestPipe");
_pipeClient.ServerMessage += PipeClientOnServerMessage;
_pipeClient.Error += PipeClientOnError;
_pipeClient.Start();
InternetExplorerBrowserEmulation.SetBrowserEmulationMode();
SuppressScriptErrors(_Browser, false);
SetWebBrowserFeatures();
GridBrrw.Children.Add(_Browser);
_Browser.ObjectForScripting = new ObjectForScripting(_pipeClient);
_Browser.LoadCompleted += new LoadCompletedEventHandler(_Browser_OnLoadCompleted);
_Browser.Navigating += _Browser_OnNavigating;
var th = new Thread(ExecuteInForeground);
th.Start();
}
private void ExecuteInForeground()
{
int i = 0;
while (i<=9)
{
Thread.Sleep(1000);
_pipeClient.PushMessage(new WebMessage() {Actions = "allo"});
i++;
}
}
private void _Browser_OnNavigating(object sender, NavigatingCancelEventArgs e)
{
if (IsClick)
{
var mes = new WebMessage { Actions = "OpenUrl" };
mes.Url = e.Uri.AbsoluteUri;
_pipeClient.PushMessage(mes);
e.Cancel = false;
}
return;
e.Cancel = false;
}
private void _Browser_OnLoadCompleted(object sender, NavigationEventArgs e)
{
try
{
var br = sender as WebBrowser;
if (br?.Source != null && br.Source.AbsoluteUri != e.Uri.AbsoluteUri)
{
MessageBox.Show($"Source = {br.Source.AbsoluteUri},\r\n AbsoluteUri = {e.Uri.AbsoluteUri}");
return;
}
Document = (HTMLDocument)br.Document;
if (!string.IsNullOrEmpty(FindElement))
{
var node = HtmlNode.CreateNode(FindElement);
while (GetElement(node) == null)
{
System.Windows.Forms.Application.DoEvents();
}
}
if (WaitAjax)
{
ConnectToAjax();
return;
}
if (Sleep > 0)
{
var time = TimeSpan.FromSeconds(Sleep);
Thread.Sleep(time);
}
var mes = new WebMessage { Actions = "Load" };
mes.Title = Document.title;
mes.Url = br.Source.AbsoluteUri;
mes.Domain = br.Source.Host.Replace("http", "").Replace("http://", "").Replace("https://", "").Replace("https", "");
mes.Fovicon = $"http://www.google.com/s2/favicons?domain={mes.Domain}";
if (Document != null)
{
var htmls = Document.getElementsByTagName("html");
if (htmls != null && htmls.length > 0)
{
var html = htmls.item(0) as IHTMLElement;
mes.Html = html.outerHTML;
}
}
_pipeClient.PushMessage(mes);
}
catch (Exception ex)
{
throw ex;
}
}
Event Navigating firing, ExecuteInForeground sends messages, but LoadCompleted event is not firing. Could this be due to the settings window - Property = "ResizeMode" Value = "NoResize". What am I doing wrong?
I am writing an app which should be able to run multiple views to edit different documents each in their own window. I've wrote some code which works, but I'm having some problems with it. The code I wrote is based upon the Multiple Views sample provided by Microsoft (https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/MultipleViews).
I have mainly two problems. The first one is if I close the main view, that is the first window that was open when the application was launched, then I cannot open any new views/windows by clicking in the app tile or opening an associated file type, until I close all views/windows and relaunch the app. The second one, is that when I try to open a new view/window from MainPage.xaml.cs, the app just crashes.
The code that I use to manage the views in App.xaml.cs is the following:
sealed partial class App : Application
{
//I use this boolean to determine if the application has already been launched once
private bool alreadyLaunched = false;
public ObservableCollection<ViewLifetimeControl> SecondaryViews = new ObservableCollection<ViewLifetimeControl>();
private CoreDispatcher mainDispatcher;
public CoreDispatcher MainDispatcher
{
get
{
return mainDispatcher;
}
}
private int mainViewId;
public int MainViewId
{
get
{
return mainViewId;
}
}
public App()
{
this.InitializeComponent();
this.Suspending += OnSuspending;
}
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
alreadyLaunched = true;
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
else if(alreadyLaunched)
{
var selectedView = await createMainPageAsync();
if (null != selectedView)
{
selectedView.StartViewInUse();
var viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(
selectedView.Id,
ViewSizePreference.Default,
ApplicationView.GetForCurrentView().Id,
ViewSizePreference.Default
);
await selectedView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var currentPage = (MainPage)((Frame)Window.Current.Content).Content;
Window.Current.Activate();
});
selectedView.StopViewInUse();
}
}
// Ensure the current window is active
Window.Current.Activate();
}
protected override async void OnFileActivated(FileActivatedEventArgs args)
{
base.OnFileActivated(args);
if (alreadyLaunched)
{
//Frame rootFrame = Window.Current.Content as Frame;
//((MainPage)rootFrame.Content).OpenFileActivated(args);
var selectedView = await createMainPageAsync();
if (null != selectedView)
{
selectedView.StartViewInUse();
var viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(
selectedView.Id,
ViewSizePreference.Default,
ApplicationView.GetForCurrentView().Id,
ViewSizePreference.Default
);
await selectedView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var currentPage = (MainPage)((Frame)Window.Current.Content).Content;
Window.Current.Activate();
currentPage.OpenFileActivated(args);
});
selectedView.StopViewInUse();
}
}
else
{
Frame rootFrame = new Frame();
rootFrame.Navigate(typeof(MainPage), args);
Window.Current.Content = rootFrame;
Window.Current.Activate();
alreadyLaunched = true;
}
}
partial void Construct();
partial void OverrideOnLaunched(LaunchActivatedEventArgs args, ref bool handled);
partial void InitializeRootFrame(Frame frame);
partial void OverrideOnLaunched(LaunchActivatedEventArgs args, ref bool handled)
{
// Check if a secondary view is supposed to be shown
ViewLifetimeControl ViewLifetimeControl;
handled = TryFindViewLifetimeControlForViewId(args.CurrentlyShownApplicationViewId, out ViewLifetimeControl);
if (handled)
{
var task = ViewLifetimeControl.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
Window.Current.Activate();
});
}
}
partial void InitializeRootFrame(Frame frame)
{
mainDispatcher = Window.Current.Dispatcher;
mainViewId = ApplicationView.GetForCurrentView().Id;
}
bool TryFindViewLifetimeControlForViewId(int viewId, out ViewLifetimeControl foundData)
{
foreach (var ViewLifetimeControl in SecondaryViews)
{
if (ViewLifetimeControl.Id == viewId)
{
foundData = ViewLifetimeControl;
return true;
}
}
foundData = null;
return false;
}
private async Task<ViewLifetimeControl> createMainPageAsync()
{
ViewLifetimeControl viewControl = null;
await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// This object is used to keep track of the views and important
// details about the contents of those views across threads
// In your app, you would probably want to track information
// like the open document or page inside that window
viewControl = ViewLifetimeControl.CreateForCurrentView();
viewControl.Title = DateTime.Now.ToString();
// Increment the ref count because we just created the view and we have a reference to it
viewControl.StartViewInUse();
var frame = new Frame();
frame.Navigate(typeof(MainPage), viewControl);
Window.Current.Content = frame;
// This is a change from 8.1: In order for the view to be displayed later it needs to be activated.
Window.Current.Activate();
//ApplicationView.GetForCurrentView().Title = viewControl.Title;
});
((App)App.Current).SecondaryViews.Add(viewControl);
return viewControl;
}
void OnNavigationFailed(object sender, NavigationFailedEventArgs e)
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
}
private void OnSuspending(object sender, SuspendingEventArgs e)
{
var deferral = e.SuspendingOperation.GetDeferral();
//TODO: Save application state and stop any background activity
deferral.Complete();
}
//I call this function from MainPage.xaml.cs to try to open a new window
public async void LoadNewView()
{
var selectedView = await createMainPageAsync();
if (null != selectedView)
{
selectedView.StartViewInUse();
var viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(
selectedView.Id,
ViewSizePreference.Default,
ApplicationView.GetForCurrentView().Id,
ViewSizePreference.Default
);
await selectedView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var currentPage = (MainPage)((Frame)Window.Current.Content).Content;
Window.Current.Activate();
currentPage.LoadNewFile();
});
selectedView.StopViewInUse();
}
}
}
The code I use to try to launch a new view/window from MainPage.xaml.cs:
((App)App.Current).LoadNewView();
I've been reading the Microsoft documentation to try and understand what is the issue, but I still don't understand how exactly do Multiple Views work, like if the App class instantiated every time I open a new view/window.
I'd really appreciate the help.
Actually the proper way to still be able to open up new windows after the main one is closed is to use one of the overloads provided by TryShowAsStandaloneAsync.
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
// Create the newWindowId and stuff...
await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newWindowId,
ViewSizePreference.Default,
e.CurrentlyShownApplicationViewId,
ViewSizePreference.Default);
Basically, you need to specify the third parameter anchorViewId which is
the ID of the calling (anchor) window.
In this case, you just need to pass in e.CurrentlyShownApplicationViewId.
I've found the solution to my problems, and I've actually decided not to use the ViewLifeTime control that comes with the sample.
The problem is that when the Main view is closed you have to use the Dispatcher.RunAsync() method from one of the other views that are still open to run it that thread
Here's the code that I've changed in my App.xaml.cs for anyone that is interested:
public bool isMainViewClosed = false;
public ObservableCollection<CoreApplicationView> secondaryViews = new ObservableCollection<CoreApplicationView>();
//...
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
alreadyLaunched = true;
rootFrame.Navigate(typeof(MainPage), e.Arguments);
}
else if(alreadyLaunched)
{
//If the main view is closed, use the thread of one of the views that are still open
if(isMainViewClosed)
{
int newViewId = 0;
await secondaryViews[0].Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var currentPage = (MainPage)((Frame)Window.Current.Content).Content;
Window.Current.Activate();
currentPage.NewWindow();
newViewId = ApplicationView.GetForCurrentView().Id;
});
bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
}
else
{
CoreApplicationView newView = CoreApplication.CreateNewView();
int newViewId = 0;
await newView.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
Frame frame = new Frame();
frame.Navigate(typeof(MainPage), null);
Window.Current.Content = frame;
var currentPage = (MainPage)((Frame)Window.Current.Content).Content;
Window.Current.Activate();
secondaryViews.Add(CoreApplication.GetCurrentView());
newViewId = ApplicationView.GetForCurrentView().Id;
});
bool viewShown = await ApplicationViewSwitcher.TryShowAsStandaloneAsync(newViewId);
}
}
Window.Current.Activate();
}
Optionally you can use multiple instances for your application. You can synchronize settings changes as I have described here.
don't View(your)Lifetime away ... cheers,
int idCreate = 0; List<int> idSaved = new List<int>();
protected override async void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame == null)
{
rootFrame = new Frame();
rootFrame.NavigationFailed += OnNavigationFailed;
Window.Current.Content = rootFrame;
}
if (rootFrame.Content == null)
{
rootFrame.Navigate(typeof(MainPage), e.Arguments);
idSaved.Add(ApplicationView.GetForCurrentView().Id);
}
else
{
var create = CoreApplication.CreateNewView();
await create.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
var frame = new Frame();
frame.Navigate(typeof(MainPage), e.Arguments);
Window.Current.Content = frame;
Window.Current.Activate();
idCreate = ApplicationView.GetForCurrentView().Id;
});
for(int i = idSaved.Count - 1; i >= 0; i--)
if (await ApplicationViewSwitcher.TryShowAsStandaloneAsync(
idCreate, ViewSizePreference.UseMinimum,
idSaved[i], ViewSizePreference.UseMinimum)
) break;
idSaved.Add(idCreate);
}
Window.Current.Activate();
}