/// <summary> /// Sets up the connection between view and viewModel, shows the view as a metro dialog, /// calls <paramref name="onShown"/> and waits for the dialog to be closed. /// </summary> public static async Task <T> ShowDialogAsync <T>(this MetroWindow window, CloseableViewModel <T> viewModel, BaseMetroDialog view, Action onShown = null) { view.DataContext = viewModel; // Undefault buttons not in the dialog as they would be pressed instead of a dialog button on enter. var oldDefaults = window.FindVisualChildren <Button>().Where(b => b.IsDefault).ToList(); oldDefaults.ForEach(b => b.IsDefault = false); // Save old keyboard focus. var oldFocus = Keyboard.FocusedElement; await window.ShowMetroDialogAsync(view, new MetroDialogSettings { AnimateShow = false }); // Focus the first focusable element in the view var element = view.FindVisualChildren <UIElement>().FirstOrDefault(e => e.Focusable); element?.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => Keyboard.Focus(element))); onShown?.Invoke(); var result = await viewModel.WaitForCloseAsync(); await window.HideMetroDialogAsync(view, new MetroDialogSettings { AnimateHide = false }); // Restore IsDefault and keyboard focus. oldDefaults.ForEach(b => b.IsDefault = true); Keyboard.Focus(oldFocus); return(result); }
/// <summary> /// Creates a <see cref="CustomMessageDialog"/> inside of the current window. /// </summary> /// <param name="window">The MetroWindow</param> /// <param name="title">The title of the <see cref="CustomMessageDialog"/>.</param> /// <param name="message">The message contained within the <see cref="CustomMessageDialog"/>.</param> /// <param name="style">The type of buttons to use.</param> /// <param name="settings">Optional settings that override the global metro dialog settings.</param> /// <returns>A task promising the result of which button was pressed.</returns> public static Task <MessageDialogResult> ShowCustomMessageAsync( this MetroWindow window, string title, object message, MessageDialogStyle style = MessageDialogStyle.Affirmative, MetroDialogSettings settings = null) { settings = settings ?? window.MetroDialogOptions; var dialog = new CustomMessageDialog(window, settings) { Message = message, Title = title, ButtonStyle = style }; var tcs = new TaskCompletionSource <MessageDialogResult>(); dialog.WaitForButtonPressAsync().ContinueWith(async task => { await window.Invoke(async() => { await window.HideMetroDialogAsync(dialog); // The focus may have changed and altered the command-routing path, so suggest that command conditions be re-evaluated. // Note that this may no longer necessary since making the "current document" content control // focusable (which fixed a bunch of command condition re-evaluation issues). CommandManager.InvalidateRequerySuggested(); }); tcs.TrySetResult(task.Result); }); window.ShowMetroDialogAsync(dialog, settings ?? window.MetroDialogOptions); return(tcs.Task); }
/// <summary> /// Sets up the connection between view and viewModel, shows the view as a metro dialog, /// calls <paramref name="onShown"/> and waits for the dialog to be closed. /// </summary> public static async Task <T> ShowDialogAsync <T>(this MetroWindow window, CloseableViewModel <T> viewModel, BaseMetroDialog view, Action onShown = null) { view.DataContext = viewModel; // Undefault buttons not in the dialog as they would be pressed instead of a dialog button on enter. var oldDefaults = window.FindVisualChildren <Button>().Where(b => b.IsDefault).ToList(); oldDefaults.ForEach(b => b.IsDefault = false); // Clear keyboard focus as they focused element is pressed instead of a dialog element on enter. var oldFocus = Keyboard.FocusedElement; Keyboard.ClearFocus(); await window.ShowMetroDialogAsync(view, new MetroDialogSettings { AnimateShow = false }); DialogParticipation.SetRegister(view, viewModel); onShown?.Invoke(); var result = await viewModel.WaitForCloseAsync(); await window.HideMetroDialogAsync(view, new MetroDialogSettings { AnimateHide = false }); DialogParticipation.SetRegister(view, null); // Restore IsDefault and keyboard focus. oldDefaults.ForEach(b => b.IsDefault = true); Keyboard.Focus(oldFocus); return(result); }
/// <summary> /// Show the required dialog. /// </summary> /// <typeparam name="TResult">The type of result to return.</typeparam> /// <param name="viewModel">The view model ascociated with the view.</param> public async Task <TResult> ShowDialog <TResult>(DialogViewModel <TResult> viewModel) { // Locate the ascociated view. var viewType = ViewLocator.LocateTypeForModelType(viewModel.GetType(), null, null); var dialog = (BaseMetroDialog)Activator.CreateInstance(viewType); if (dialog == null) { throw new InvalidOperationException( String.Format("The view {0} belonging to view model {1} " + "does not inherit from {2}", viewType, viewModel.GetType(), typeof(BaseMetroDialog))); } dialog.DataContext = viewModel; // Show the metro window. MetroWindow firstMetroWindow = Application.Current.Windows.OfType <MetroWindow>().First(); await firstMetroWindow.ShowMetroDialogAsync(dialog); TResult result = await viewModel.Task; await firstMetroWindow.HideMetroDialogAsync(dialog); return(result); }
public static async Task <bool> ShowAddGameDialog(this MetroWindow window, Deck deck) { if (deck == null) { return(false); } var dialog = new AddGameDialog(deck); await window.ShowMetroDialogAsync(dialog, new MetroDialogSettings { AffirmativeButtonText = "save", NegativeButtonText = "cancel" }); var game = await dialog.WaitForButtonPressAsync(); await window.HideMetroDialogAsync(dialog); if (game == null) { return(false); } deck.DeckStats.AddGameResult(game); if (Config.Instance.HearthStatsAutoUploadNewGames) { if (game.GameMode == GameMode.Arena) { HearthStatsManager.UploadArenaMatchAsync(game, deck, true, true).Forget(); } else { HearthStatsManager.UploadMatchAsync(game, deck.GetSelectedDeckVersion(), true, true).Forget(); } } DeckStatsList.Save(); Core.MainWindow.DeckPickerList.UpdateDecks(forceUpdate: new[] { deck }); return(true); }
public static async Task <TClose> ShowDialogAsync <TOpen, TClose>( this CustomDialog dialog , TOpen parameters = default , MetroDialogSettings settings = null) { if (!(dialog.DataContext is DialogViewModel <TOpen, TClose> vm)) { throw new DialogViewModelNotFoundException(dialog.DataContext.GetType().ToString()); } if (settings == null) { settings = MetroDialogSettingsFactory.Create(); } MetroWindow window = WindowHelper.GetMainWindow(); vm.OnDialogOpened(parameters); await window.ShowMetroDialogAsync(dialog, settings); TClose resultParameters = await vm.ResultParameterTask; await window.HideMetroDialogAsync(dialog, settings); return(resultParameters); }
private object ShowDialogMetroDialogImpl <T>(T viewModel) where T : ClosableViewModel { Type windowType = registedDialogs[typeof(T)]; Control dialogContent = (Control)Activator.CreateInstance(windowType); dialogContent.DataContext = viewModel; MetroWindow mainWindow = App.Current.MainWindow as MetroWindow; if (mainWindow == null) { throw new InvalidOperationException("The MainWindow must be a MetroWindow"); } CustomDialog dialog = new CustomDialog(); dialog.Content = dialogContent; dialog.Title = viewModel.Header; mainWindow.ShowMetroDialogAsync(dialog); EventHandler closeHandler = null; closeHandler = (sender, e) => { mainWindow.HideMetroDialogAsync(dialog); viewModel.RequestClose -= closeHandler; }; viewModel.RequestClose += closeHandler; return(dialog); }
private async void ExecuteUpdateAsync() { if (SelectedCategory.QtyStart == null || SelectedCategory.Price == null || SelectedCategory.Cost == null || SelectedCategory.RequestLimit == null) { return; } if (_selectedCategory.SuppliesCategories.Count == 0 && _selectedCategory.SalesCategories.Count == 0) { _selectedCategory.Qty = _selectedCategory.QtyStart; } _categoryServ.UpdateCategory(_selectedCategory); _categoriesSuggestions.Add(_selectedCategory.Name); await _currentWindow.HideMetroDialogAsync(_categoryUpdateDialog); Load(); }
public MarkdownDialog(MetroWindow parentWindow, MetroDialogSettings settings = null) : base(parentWindow, settings) { ParentWindow = parentWindow; InitializeComponent(); CommandBindings.Add(new CommandBinding(NavigationCommands.GoToPage, (sender, e) => System.Diagnostics.Process.Start((string)e.Parameter))); PART_AffirmativeButton.Click += (sender, args) => ParentWindow.HideMetroDialogAsync(this); PART_NegativeButton.Click += (sender, args) => ParentWindow.HideMetroDialogAsync(this); if (settings == null) { return; } AffirmativeButtonText = settings.AffirmativeButtonText; NegativeButtonText = settings.NegativeButtonText; }
private void TryHide() { if (!_isShown) { return; } _owner.HideMetroDialogAsync(this); _isShown = false; }
private async void ExecuteUpdateAsync() { if (SelectedCompany == null || SelectedCategory.QtyStart == null || SelectedCategory.Price == null || SelectedCategory.Cost == null || SelectedCategory.RequestLimit == null) { return; } if (!(_categoryServ.IsExistInSupplies(_selectedCategory.ID) || _categoryServ.IsExistInSales(_selectedCategory.ID))) { _selectedCategory.Qty = _selectedCategory.QtyStart; } _selectedCategory.Stock = SelectedStock; _selectedCategory.Company = SelectedCompany; _categoryServ.UpdateCategory(_selectedCategory); await _currentWindow.HideMetroDialogAsync(_categoryUpdateDialog); Load(); }
public static async void StartClientThenServer() { //detect if a client is already started on this computer if (System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties().GetActiveUdpListeners().Any(p => p.Port == 14999)) { if (!simultaneousErrorDialog.IsVisible) { await window.ShowMetroDialogAsync(simultaneousErrorDialog); } simultaneousErrorDialog.MessageText.Content = "Error when starting client- UDP port already occupied. \nCheck whether there is another instance running"; Console.Out.WriteLine("[NetworkManager] error when starting client- UDP port already occupied. Check whether there is another instance running"); return; } if (!connectionEnabled) { return; } client = new Client(); client.ServerFound += ServerFound; client.ServerConnected += ServerConnected; client.ServerDisconnected += ServerDisconnected; client.MessageReceivedFromServer += MessageReceivedFromServer; //Auto give up finding client after 10 second DispatcherTimer timer = new DispatcherTimer(); timer.Interval = TimeSpan.FromSeconds(5 + 4 * (clientNumber + 2)); timer.Start(); timer.Tick += new EventHandler(async delegate(object s, EventArgs a) { timer.Stop(); if (connected) { return; } Console.Out.WriteLine("[NetworkManager] No server found. Terminating client. Start as Server instead"); //close the client if (progressingDialog.IsVisible) { await window.HideMetroDialogAsync(progressingDialog); } client.StopUDP(); //start as a server StartServer(null, null); }); if (!progressingDialog.IsVisible) { await window.ShowMetroDialogAsync(progressingDialog); } progressingDialog.MessageText.Content = "Finding Server:\nPosition in queue: " + (clientNumber + 2); }
private async void ExecuteCloseDialogAsync(string parameter) { switch (parameter) { case "Add": await _currentWindow.HideMetroDialogAsync(_salespersonAddDialog); Load(); break; case "AccountShow": await _currentWindow.HideMetroDialogAsync(_salespersonAccountShowDialog); break; default: break; } }
private async void ExecuteSignInAsync() { if (_currentedUser.ID == null || _currentedUser.Password == null) { return; } var user = userServ.GetUser(); if (_currentedUser.ID == user.ID && _currentedUser.Password == user.Password) { await _currentWindow.HideMetroDialogAsync(_loginDialog); var supply = supplyFutureServ.GetSupplyFuture(); if (supply != null) { IsFuuture = "Red"; await _currentWindow.ShowMessageAsync("تنبيه", "نرجو مراجعه الفواتير الآجله لدفع المتبقى", MessageDialogStyle.Affirmative, new MetroDialogSettings() { AffirmativeButtonText = "موافق", DialogMessageFontSize = 25, DialogTitleFontSize = 30 }); } else { IsFuuture = "White"; } } else { await _currentWindow.HideMetroDialogAsync(_loginDialog); await _currentWindow.ShowMessageAsync("فشل الدخول", "يوجد خطأ فى الاسم أو الرقم السرى يرجى التأكد من البيانات", MessageDialogStyle.Affirmative, new MetroDialogSettings() { AffirmativeButtonText = "موافق", DialogMessageFontSize = 25, DialogTitleFontSize = 30 }); await _currentWindow.ShowMetroDialogAsync(_loginDialog); } }
static ReactiveCommand <bool?> CreateCommand(BaseMetroDialog dialog, MetroWindow window, TaskCompletionSource <bool?> tcs) { var command = ReactiveCommand.CreateAsyncTask(async x => { await window.HideMetroDialogAsync(dialog); return((bool?)x); }); SetupCommand(tcs, command); return(command); }
public static async Task <ImportingChoice?> ShowImportingChoiceDialog(this MetroWindow window) { var dialog = new ImportingChoiceDialog(); await window.ShowMetroDialogAsync(dialog); var type = await dialog.WaitForButtonPressAsync(); await window.HideMetroDialogAsync(dialog); return(type); }
private async void ExecuteCloseDialogAsync(string parameter) { switch (parameter) { case "Category": await _currentWindow.HideMetroDialogAsync(_categoryDialog); break; case "Recall": await _currentWindow.HideMetroDialogAsync(_saleRecallDialog); State = "Normal"; RecallsQty = _saleRecallServ.GetSaleRecallsSum(ID); break; default: break; } }
public static async Task <SelectLanguageOperation> ShowSelectLanguageDialog(this MetroWindow window) { var dialog = new SelectLanguageDialog(); await window.ShowMetroDialogAsync(dialog); var result = await dialog.WaitForButtonPressAsync(); await window.HideMetroDialogAsync(dialog); return(result); }
private async void ExecuteSelectCategoryAsync() { try { if (SelectedCategory == null) { return; } NewSupplyCategory.Category = SelectedCategory.Name; NewSupplyCategory.CategoryID = SelectedCategory.ID; NewSupplyCategory.Company = SelectedCategory.Company.Name; NewSupplyCategory.Cost = SelectedCategory.Cost; await _currentWindow.HideMetroDialogAsync(_categoriesDialog); OldCosts = new ObservableCollection <SupplyCategory>(_supplyCategoryServ.GetOldCosts(_newSupplyCategory.CategoryID, _selectedSupply.ClientID)); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
private async void ExecuteUpdateAsync() { if (AccountStart == null) { return; } if (_accountStartType == true) { _selectedClient.AccountStart = _accountStart; } else { _selectedClient.AccountStart = -_accountStart; } _clientServ.UpdateClient(_selectedClient); _namesSuggestions.Add(_selectedClient.Name); await _currentWindow.HideMetroDialogAsync(_clientUpdateDialog); Load(); }
private async void ExecuteSelectCategoryAsync() { if (SelectedCategory == null) { return; } NewSupplyOfferCategory.Category = SelectedCategory.Name; NewSupplyOfferCategory.CategoryID = SelectedCategory.ID; NewSupplyOfferCategory.Company = SelectedCategory.Company.Name; NewSupplyOfferCategory.Cost = SelectedCategory.Cost; await _currentWindow.HideMetroDialogAsync(_categoriesDialog); if (SelectedClient != null) { OldCosts = new ObservableCollection <SupplyCategory>(_supplyCategoryServ.GetOldCosts(_newSupplyOfferCategory.CategoryID, _selectedClient.ID)); } else { OldCosts = new ObservableCollection <SupplyCategory>(); } }
private async void ExecuteUpdateAsync() { try { if (ItemUpdate.Name == null || ItemUpdate.Price == null) { return; } using (var unitOfWork = new UnitOfWork(new GeneralDBContext())) { var item = unitOfWork.Items.SingleOrDefault(s => s.Name == ItemUpdate.Name && s.ID != ItemUpdate.ID); if (item != null) { await currentWindow.ShowMessageAsync("فشل الإضافة", "هذاالصنف موجود مسبقاً", MessageDialogStyle.Affirmative, new MetroDialogSettings() { AffirmativeButtonText = "موافق", DialogMessageFontSize = 25, DialogTitleFontSize = 30 }); } else { SelectedItem.Item.Name = ItemUpdate.Name; SelectedItem.Item.Price = ItemUpdate.Price; SelectedItem.Item.IsAvailable = ItemUpdate.IsAvailable; SelectedItem.Item.CategoryID = ItemUpdate.CategoryID; SelectedItem.Item.Category = ItemUpdate.Category; unitOfWork.Items.Edit(_selectedItem.Item); unitOfWork.Complete(); await currentWindow.HideMetroDialogAsync(itemUpdateDialog); Load(); } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public static async Task <string> ShowFolderSelectAsync(this MetroWindow window, string title, string message, string rootFolder, MetroDialogSettings settings = null) { settings = settings ?? window.MetroDialogOptions; var dialog = new FolderSelectDialog(window, settings) { Title = title, Message = message, RootFolder = rootFolder }; var result = await window.ShowMetroDialogAsync(dialog).ContinueWith(x => dialog.WaitForButtonPressAsync()).Unwrap(); await window.HideMetroDialogAsync(dialog); return(result); }
private async void ExecuteCloseDialogAsync(string parameter) { switch (parameter) { case "Details": await _currentWindow.HideMetroDialogAsync(_safeDetailsDialog); break; default: break; } }
private async void ExecuteCloseDialogAsync(string parameter) { switch (parameter) { case "Add": await _currentWindow.HideMetroDialogAsync(_companyAddDialog); Load(); break; default: break; } }
private async void ExecuteUpdateAsync() { try { if (CategoryUpdate.Name == null) { return; } using (var unitOfWork = new UnitOfWork(new GeneralDBContext())) { var category = unitOfWork.Categories.SingleOrDefault(s => s.Name == CategoryUpdate.Name && s.ID != CategoryUpdate.ID); if (category != null) { await currentWindow.ShowMessageAsync("فشل الإضافة", "هذاالنوع موجود مسبقاً", MessageDialogStyle.Affirmative, new MetroDialogSettings() { AffirmativeButtonText = "موافق", DialogMessageFontSize = 25, DialogTitleFontSize = 30 }); } else { SelectedCategory.Category.Name = CategoryUpdate.Name; unitOfWork.Categories.Edit(_selectedCategory.Category); unitOfWork.Complete(); await currentWindow.HideMetroDialogAsync(categoryUpdateDialog); Load(); } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
public async Task <bool> showmessageauto(string msg, int ms) { MetroWindow window = (MahApps.Metro.Controls.MetroWindow)System.Windows.Application.Current.MainWindow; //var dialog = (BaseMetroDialog)window.Resources["CustomDialogTest"]; CustomDialog cdlg = new CustomDialog(); cdlg.Title = msg; await window.ShowMetroDialogAsync(cdlg); await Task.Delay(ms); await window.HideMetroDialogAsync(cdlg); return(true); }
public async Task <object> Execute(MetroWindow window, object args) { var settings = new MetroDialogSettings(); var dlg = new InfoDialog(); var ctrl = dlg.DataContext as IViewController; if (ctrl != null) { ctrl.CloseRequested += async(s, e) => { await window.HideMetroDialogAsync(dlg, settings); }; } await window.ShowMetroDialogAsync(dlg, settings); return(null); }
public async Task ShowDialogAsync(DialogViewModelBase viewModel) { var viewType = ViewLocator.LocateTypeForModelType(viewModel.GetType(), null, null); var dialog = (BaseMetroDialog)Activator.CreateInstance(viewType); if (dialog == null) { throw new InvalidOperationException( $"The view {viewType} belonging to view model {viewModel.GetType()} " + $"does not inherit from {typeof(BaseMetroDialog)}"); } dialog.DataContext = viewModel; MetroWindow firstMetroWindow = Application.Current.Windows.OfType <MetroWindow>().First(); await firstMetroWindow.ShowMetroDialogAsync(dialog); await viewModel.Task; await firstMetroWindow.HideMetroDialogAsync(dialog); }
private async void ExecuteCloseDialogAsync(string parameter) { try { switch (parameter) { case "Add": await currentWindow.HideMetroDialogAsync(safeAddDialog); break; default: break; } } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }