protected override void BeforeQueryStatus(Microsoft.VisualStudio.Shell.OleMenuCommand command, SelectedItems selection) { var activeDocument = dte.ActiveDocument; if (activeDocument == null || activeDocument.ProjectItem == null) { command.Visible = false; return; } if (selection.Count != 1) { command.Enabled = false; return; } if (IsFeatureFile(activeDocument.ProjectItem)) { command.Enabled = goToStepDefinitionCommand.IsEnabled(activeDocument); command.Text = "Go To Step Definition"; } else if (IsCodeFile(activeDocument.ProjectItem)) { command.Enabled = goToStepsCommand.IsEnabled(activeDocument); command.Text = "Go To Matching SpecFlow Steps"; } else { command.Visible = false; } }
private bool IsInSpecFlowProject(SelectedItems selection) { for (int selectionIndex = 1; selectionIndex <= selection.Count; selectionIndex++) if (IsInSpecFlowProject(selection.Item(selectionIndex))) return true; return false; }
protected override void Invoke(OleMenuCommand command, SelectedItems selection) { var selectedItem = selection.Item(1); if (selectedItem.ProjectItem != null) testRunnerEngine.RunFromProjectItem(selectedItem.ProjectItem, false); if (selectedItem.Project != null) testRunnerEngine.RunFromProject(selectedItem.Project, false); }
protected override void BeforeQueryStatus(OleMenuCommand command, SelectedItems selection) { base.BeforeQueryStatus(command, selection); if (command.Visible) { if (dte.ActiveDocument == null || dte.ActiveDocument.ProjectItem == null || !ContextDependentNavigationCommand.IsFeatureFile(dte.ActiveDocument.ProjectItem)) command.Visible = false; } }
protected override void BeforeQueryStatus(OleMenuCommand command, SelectedItems selection) { base.BeforeQueryStatus(command, selection); if (command.Visible) { var selectedItem = selection.Item(1); if (selectedItem.ProjectItem != null && VsxHelper.IsPhysicalFile(selectedItem.ProjectItem) && !ContextDependentNavigationCommand.IsFeatureFile(selectedItem.ProjectItem)) command.Visible = false; //only show it in feature file, folder or project nodes } }
protected override void BeforeQueryStatus(OleMenuCommand command, SelectedItems selection) { if (!IsInSpecFlowProject(selection)) { command.Visible = false; return; } if (selection.Count == 1) { command.Enabled = true; } }
protected override void Invoke(Microsoft.VisualStudio.Shell.OleMenuCommand command, SelectedItems selection) { var activeDocument = dte.ActiveDocument; if (IsFeatureFile(activeDocument.ProjectItem)) { goToStepDefinitionCommand.Invoke(activeDocument); } else if (IsCodeFile(activeDocument.ProjectItem)) { goToStepsCommand.Invoke(activeDocument); } }
protected override void Invoke(OleMenuCommand command, SelectedItems selection) { var selectedItem = selection.Item(1); if (selectedItem.Project == null) return; var projectScope = projectScopeFactory.GetProjectScope(selectedItem.Project) as VsProjectScope; if (projectScope == null) return; if (!projectScope.FeatureFilesTracker.IsInitialized) { MessageBox.Show("Feature files are still being analyzed. Please wait.", "Regenerate Feature Files"); return; } projectScope.FeatureFilesTracker.ReGenerateAll(); }
bool CanRemoveUserRole() { return(SelectedItems.Any()); }
/// <summary> /// Draw the window. /// </summary> protected virtual void OnGUI() { InitializeStyles(); if (!String.IsNullOrEmpty(Caption)) { EditorGUILayout.BeginHorizontal(); EditorGUILayout.SelectableLabel(Caption); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); } EditorGUILayout.BeginVertical(); scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); int displayIndex = 0; foreach (var indexAndItem in sortedItems) { var item = indexAndItem.Value.Key; var display = indexAndItem.Value.Value; bool selected = SelectedItems.Contains(item); EditorGUILayout.BeginHorizontal( selected ? selectedItemStyles[displayIndex % selectedItemStyles.Length] : unselectedItemStyles[displayIndex % unselectedItemStyles.Length]); bool currentlySelected = EditorGUILayout.ToggleLeft(display, selected); if (currentlySelected != selected) { if (currentlySelected) { SelectedItems.Add(item); } else { SelectedItems.Remove(item); } } EditorGUILayout.EndHorizontal(); displayIndex++; } EditorGUILayout.EndScrollView(); EditorGUILayout.EndVertical(); EditorGUILayout.BeginHorizontal(); if (GUILayout.Button("All")) { SelectAll(); } if (GUILayout.Button("None")) { SelectNone(); } EditorGUILayout.Space(); EditorGUILayout.Space(); bool cancel = GUILayout.Button(CancelLabel); bool apply = GUILayout.Button(ApplyLabel); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); if (cancel || apply) { if (cancel && OnCancel != null) { OnCancel(); } if (apply && OnApply != null) { OnApply(); } Close(); } }
private bool MessagesForwardCanExecute() { return(SelectedItems.Count > 0 && SelectedItems.All(x => x.CanBeForwarded)); }
internal override void OnSelectedItemChanged(object oldSelectedItem, object selectedItem, bool updateItemSelectedState) { if (_modifyingSelectionInternally) { return; } if (IsSelectionMultiple) { var items = GetItems(); if (selectedItem == null || items.Contains(selectedItem)) { object[] removedItems = null; object[] addedItems = null; try { _modifyingSelectionInternally = true; removedItems = SelectedItems.Except(selectedItem).ToObjectArray(); var isRealSelection = selectedItem != null || items.Contains(null); addedItems = SelectedItems.Contains(selectedItem) || !isRealSelection ? new object[0] : new[] { selectedItem }; SelectedItems.Clear(); if (isRealSelection) { SelectedItems.Add(selectedItem); } } finally { _modifyingSelectionInternally = false; } //Invoke event after resetting flag, in case callbacks in user code modify the collection if (addedItems.Length > 0 || removedItems.Length > 0) { InvokeSelectionChanged(removedItems, addedItems); } } else { SelectedItem = oldSelectedItem; } } else { try { _modifyingSelectionInternally = true; if (selectedItem != null) { SelectedItems.Update(new[] { selectedItem }); } else { SelectedItems.Clear(); } } finally { _modifyingSelectionInternally = false; } base.OnSelectedItemChanged( oldSelectedItem: oldSelectedItem, selectedItem: selectedItem, updateItemSelectedState: true); } }
protected override void Invoke(OleMenuCommand command, SelectedItems selection) { invoke(command, selection); }
private void ToggleItem([NotNull] TreeViewItem item) { if (item.DataContext == null) { return; } var itemsToUnselect = SelectionMode == SelectionMode.Single ? new List <object>(SelectedItems.Cast <object>()) : new List <object>(); if (SelectedItems.Contains(item.DataContext)) { itemsToUnselect.Add(item.DataContext); ModifySelection(new List <object>(), itemsToUnselect); } else { ModifySelection(new List <object>(1) { item.DataContext }, itemsToUnselect); } }
protected override void BeforeQueryStatus(OleMenuCommand command, SelectedItems selection) { if (beforeQueryStatus != null) beforeQueryStatus(command, selection); }
/// <summary> /// generazione fatture da ordine di scarico /// </summary> private void GeneraFatturaDaOrdineScarico() { var fatt = SelectedItem; if (SelectedItems.Count > 1) { if (!MessageManager.QuestionMessage("Vuoi generare fattura per i documenti selezionati. Vuoi proseguire?")) { return; } } if (!MessageManager.QuestionMessage(@"Generando la fattura, il documento\i di carico non sarà più modificabile. Vuoi proseguire?")) { return; } List <Fattura> list = new List <Fattura>(); if (SelectedItems.Count > 1) { list = SelectedItems.Select(a => a.Entity).ToList(); } else { list.Add(fatt); } list = list.Where(a => !a.ChiusaSpedita && a.TipoDocumento == EnTipoDocumento.OrdineDiScarico).ToList(); if (list.Where(a => !a.ChiusaSpedita).Select(a => a.ClienteFornitoreID).Distinct().Count() > 0) { if (!MessageManager.QuestionMessage("Vuoi generare fattura per i clienti selezionati. " + "I documenti chiusi e non del tipo 'Ordine di carico' non saranno presi in considerazione. Vuoi proseguire?")) { return; } } if (list.Count() == 0) { return; } using (var saveEnt = new SaveEntityManager()) { bool save = false; var listFatt = new List <Library.Entity.Fattura>(); foreach (var ordScaricoListFornitore in list.GroupBy(a => a.ClienteFornitoreID).Select(a => new { a.Key, Fatture = a })) { var fattExt = new Library.Entity.Fattura(); fattExt.ClienteFornitoreID = ordScaricoListFornitore.Key; fattExt.TipoDocumento = Library.Entity.EnTipoDocumento.FatturaDiCortesia; fattExt.Data = DateTime.Now; fattExt.Codice = ControllerFatturazione.CalcolaCodice(fattExt); var fornitore = saveEnt.UnitOfWork.SoggettiRepository.Find(a => a.ID == fattExt.ClienteFornitoreID).Select(a => new { a.RagioneSociale, a.CodiceFiscale, a.PIVA }).FirstOrDefault(); fattExt.RagioneSociale = fornitore.RagioneSociale; fattExt.PIVA = fornitore.PIVA; saveEnt.UnitOfWork.FatturaRepository.Add(fattExt); saveEnt.SaveEntity(""); listFatt.Add(fattExt); foreach (var ordScarico in ordScaricoListFornitore.Fatture) { var righeOrdScarico = saveEnt.UnitOfWork.FattureRigheRepository.Find(a => a.FatturaID == ordScarico.ID); foreach (var itemRigaScarico in righeOrdScarico) { var riga = (new Library.Entity.FatturaRiga() { ArticoloID = itemRigaScarico.ArticoloID, Descrizione = itemRigaScarico.Descrizione, Qta = itemRigaScarico.Qta, Fattura = fattExt, PrezzoUnitario = itemRigaScarico.PrezzoUnitario, IvaApplicata = itemRigaScarico.IvaApplicata, }); saveEnt.UnitOfWork.FattureRigheRepository.Add(riga); } save = true; /*chiudo l'ordine di scarico originale*/ var ordScarDb = saveEnt.UnitOfWork.FatturaRepository.Find(a => a.ID == ordScarico.ID).First(); ordScarDb.ChiusaSpedita = true; saveEnt.UnitOfWork.FatturaRepository.Update(ordScarDb); } if (save) { saveEnt.SaveEntity(""); } } foreach (var item in listFatt.Distinct()) { ControllerFatturazione.CalcolaTotali(item); saveEnt.UnitOfWork.FatturaRepository.Update(item); } if (save) { saveEnt.SaveEntity("Generati gli ordini di acquisto!"); } } }
private void printRotaToolStripMenuItem_Click(object sender, EventArgs e) { if (SelectedItems.Count() == 0) { return; } RotaPrintMenuFrm frm = new RotaPrintMenuFrm(); if (frm.ShowDialog() != DialogResult.OK) { return; } int[] Weeks; //get an int array of week numbers if (frm.SelectedPrintSelection == RotaPrintMenuFrm.PrintSelection.AllWeeks) { Weeks = Enumerable.Range(1, Settings.Instance.rotaweekcount).ToArray(); // new int[] { 1, 2, 3, 4, 5, 6 }; } else { Weeks = frm.SelectedWeeks; } //get how many pages there will be (amount of weeks * amount of workers) int totalPages = SelectedItems.Count() * Weeks.Length; //if there are gunna be over a hundred give a warning! if (totalPages > 100) { if (MessageBox.Show("You are about to generate rather a large amount of rota pages (" + totalPages.ToString() + ").\r\nThis may take a little time. Press Yes to continue", "Rota Generation", MessageBoxButtons.YesNo) == DialogResult.No) { return; } } //sort the weeks lowest to highest Array.Sort <int>(Weeks, new Comparison <int>( (i1, i2) => i1.CompareTo(i2) )); //create the document Document document = new Document(PageSize.A4.Rotate()); PdfWriter writer; string filename = (SelectedItems.Count() > 1 ? "multiworker" : SelectedItems.ElementAt(0).Name) + "-" + _periodstartdate.ToString("yyyyMMdd") + ".pdf"; try { writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create)); document.Open(); } catch (Exception ex) { MessageBox.Show("Failed to Open Rota Pdf Document.\r\n\r\n" + ex.Message); return; } //create some font stuff BaseFont bfTimes = BaseFont.CreateFont(BaseFont.COURIER, BaseFont.CP1252, false); iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font times_bold = new iTextSharp.text.Font(bfTimes, 8, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.BLACK); iTextSharp.text.Font times_bold_underline = new iTextSharp.text.Font(bfTimes, 8, iTextSharp.text.Font.BOLD | iTextSharp.text.Font.UNDERLINE, iTextSharp.text.BaseColor.BLACK); //iterate over each worker foreach (Worker worker in SelectedItems) { //iterate over each week foreach (int week in Weeks) { DateTime currentWeek = _periodstartdate.AddDays(7 * (week - 1)); document.Add(new Paragraph(worker.Name, times_bold)); document.Add(new Paragraph("\r\n\r\n")); PdfPTable table = new PdfPTable(8); table.WidthPercentage = 100; PdfPCell cell = new PdfPCell(new Phrase("Week " + week.ToString() + "\r\n(" + currentWeek.ToString("dd/MM/yyyy") + ")\r\n", times)); cell.Padding = 5; cell.Colspan = 8; cell.HorizontalAlignment = 1; //0=left, 1=centre, 2=right table.AddCell(cell); table.AddCell(""); Dictionary <string, string[]> serviceUserText = new Dictionary <string, string[]>(); DateTime startOfWeek = currentWeek; for (int day = 0; day < 7; day++) { string daytxt = ((System.DayOfWeek)((day + 1) % 7)).ToString(); if (worker.isDayOff(startOfWeek.AddDays(day))) { daytxt += " (Day Off)"; } table.AddCell(new Phrase(daytxt, times_bold)); } //iterate over each day of this week for (int day = 0; day < 7; day++) { //get the current day DateTime currentDay = startOfWeek.AddDays(day); //now get all the calls that are on this day for this worker! foreach (Call call in worker.Calls.Where(c => c.time >= currentDay && c.time < currentDay.AddDays(1))) { string[] dayText; string serviceusertxt = call.ServiceUser.Name + "\r\n" + call.ServiceUser.add1 + "\r\n" + call.ServiceUser.postcode; //creeate a day text for a specific service user if (!serviceUserText.TryGetValue(serviceusertxt, out dayText)) { dayText = new string [] { "", "", "", "", "", "", "" }; serviceUserText.Add(serviceusertxt, dayText); } string doubleuptext = ""; if (call.required_workers == 2) { doubleuptext = "[D: "; if (call.Workers.Count() == 1) { doubleuptext += "Unassigned"; } else { Worker otherWorker = call.Workers.Single(w => w != worker); doubleuptext += otherWorker.ShortName; } doubleuptext += "]"; } string calltxt = call.time.ToString("HH:mm") + " (" + call.duration_mins.ToString() + " min)\r\n" + doubleuptext; dayText[day] += calltxt; } } if (serviceUserText.Count == 0) { Phrase phr = new Phrase("No Calls", times); phr.Font.SetStyle(1); //bold it for dramatic effect ;) PdfPCell nocallscell = new PdfPCell(phr); nocallscell.Padding = 5; nocallscell.Colspan = 8; nocallscell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right table.AddCell(nocallscell); } else { foreach (KeyValuePair <string, string[]> entry in serviceUserText) { string serviceusername = entry.Key; string[] dayText = entry.Value; table.AddCell(new Phrase(serviceusername, times)); foreach (string text in dayText) { table.AddCell(new Phrase(text.Trim(), times)); } } } document.Add(table); if (week != Weeks[Weeks.Length - 1]) { document.NewPage(); } } document.NewPage(); } document.Close(); document.Dispose(); System.Diagnostics.Process.Start(@filename); }
private void contextMenuStrip1_Opening(object sender, CancelEventArgs e) { if (SelectedItems.Count() == 0 || (!_showContextMenu && !_showSimpleContextMenu)) { e.Cancel = true; } else { //disableToolStripMenuItem.Visible = SelectedItem.idStatus == Worker.Status.Active; //enableToolStripMenuItem.Visible = SelectedItem.idStatus == Worker.Status.Inactive; if (_showSimpleContextMenu) { editToolStripMenuItem.Visible = false; duplicateUserToolStripMenuItem.Visible = false; disableToolStripMenuItem.Visible = false; enableToolStripMenuItem.Visible = false; deleteToolStripMenuItem.Visible = false; emailRotaToolStripMenuItem.Visible = false; toolStripSeparator2.Visible = false; toolStripSeparator3.Visible = false; } else { editToolStripMenuItem.Visible = _allowOpenWorker; } // ok first load up all the groups List <WorkerGroup> groups = WorkerGroupManager.Instance.WorkerGroups; List <WorkerGroup> groupsToAdd = new List <WorkerGroup>(groups); List <WorkerGroup> groupsToRemove = new List <WorkerGroup>(); // now remove all the groups to ADD except the <new group> one for (int i = addToGroupToolStripMenuItem.DropDownItems.Count - 1; i > 0; i--) { addToGroupToolStripMenuItem.DropDownItems.RemoveAt(i); } //now remove all the groups to REMOVE. removeFromGroupToolStripMenuItem.DropDownItems.Clear(); //========================================= // Add Section // // Here we are going to be adding groups // that none of the selected workers are // part of. //========================================= //first lets get all the groups that exist in all the selected items. List <WorkerGroup> selectedItemsGroups = new List <WorkerGroup>(); // create a list of every group, some may occur multiple times. we can jsut use this to see if its for everyone foreach (Worker worker in SelectedItems) { foreach (WorkerGroup group in worker.Groups) { selectedItemsGroups.Add(group); } } while (selectedItemsGroups.Count() > 0) { //get the last group in the list WorkerGroup group = selectedItemsGroups[selectedItemsGroups.Count - 1]; selectedItemsGroups.RemoveAt(selectedItemsGroups.Count - 1); int count = 1; //now find any dupes! for (int i = selectedItemsGroups.Count - 1; i >= 0; i--) { if (selectedItemsGroups[i] == group) { count++; selectedItemsGroups.RemoveAt(i); } } if (count == SelectedItems.Count()) { //everyone selected is in this group! groupsToAdd.Remove(group); } else { //only some people were in this group //leave it in } groupsToRemove.Add(group); } foreach (WorkerGroup group in groupsToAdd) { ToolStripItem item = new ToolStripMenuItem() { Text = group.GroupName, Tag = group }; item.Click += itemAdd_Click; addToGroupToolStripMenuItem.DropDownItems.Add(item); } foreach (WorkerGroup group in groupsToRemove) { ToolStripItem item = new ToolStripMenuItem() { Text = group.GroupName, Tag = group }; item.Click += itemRemove_Click; removeFromGroupToolStripMenuItem.DropDownItems.Add(item); } //only show the remove menu if there are groups to remove! removeFromGroupToolStripMenuItem.Visible = removeFromGroupToolStripMenuItem.DropDownItems.Count != 0; } }
protected virtual void Invoke(OleMenuCommand command, SelectedItems selection) { System.Windows.MessageBox.Show("Command executed"); }
void FileStatusListView_MouseMove(object sender, MouseEventArgs e) { ListView listView = sender as ListView; //DRAG // If the mouse moves outside the rectangle, start the drag. if (dragBoxFromMouseDown != Rectangle.Empty && !dragBoxFromMouseDown.Contains(e.X, e.Y)) { if (SelectedItems.Any()) { StringCollection fileList = new StringCollection(); foreach (GitItemStatus item in SelectedItems) { string fileName = Path.Combine(Module.WorkingDir, item.Name); fileList.Add(fileName.ToNativePath()); } DataObject obj = new DataObject(); obj.SetFileDropList(fileList); // Proceed with the drag and drop, passing in the list item. DoDragDrop(obj, DragDropEffects.Copy); dragBoxFromMouseDown = Rectangle.Empty; } } //TOOLTIP if (listView != null) { var point = new Point(e.X, e.Y); var hover = listView.HitTest(point); if (hover.Item != null) { var gitItemStatus = (GitItemStatus)hover.Item.Tag; string text; if (gitItemStatus.IsRenamed || gitItemStatus.IsCopied) { text = string.Concat(gitItemStatus.Name, " (", gitItemStatus.OldName, ")"); } else { text = gitItemStatus.Name; } float fTextWidth = listView.CreateGraphics().MeasureString(text, listView.Font).Width + 17; //Use width-itemheight because the icon drawn in front of the text is the itemheight if (fTextWidth > (FileStatusListView.Width - FileStatusListView.GetItemRect(hover.Item.Index).Height)) { if (!hover.Item.ToolTipText.Equals(gitItemStatus.ToString())) { hover.Item.ToolTipText = gitItemStatus.ToString(); } } else { hover.Item.ToolTipText = ""; } } } }
protected override void InitSpecialCommands() { CopyAttachmentsCommand = new DelegateLogCommand( () => { IEventServiceClient eventServiceClient = Container.Resolve <IEventServiceClient>(); IMessageService messageService = Container.Resolve <IMessageService>(); if (SelectedItems != null && SelectedItems.Any()) { var selectedProjects = SelectedItems.ToList(); var managers = selectedProjects.Select(project => project.Manager).Distinct().ToList(); var managersOffline = new List <User>(); foreach (var manager in managers) { if (eventServiceClient.UserConnected(manager.Id) == false) { managersOffline.Add(manager); } } if (managersOffline.Any()) { var dr = messageService.ShowYesNoMessageDialog("Некоторые менеджеры не подключены", $"{managersOffline.ToStringEnum()} не подключены. Продолжаем?"); if (dr != MessageDialogResult.Yes) { return; } } managersOffline.ForEach(user => managers.Remove(user)); if (managers.Any()) { using (var fdb = new FolderBrowserDialog()) { var dialogResult = fdb.ShowDialog(); if (dialogResult == DialogResult.OK && !string.IsNullOrWhiteSpace(fdb.SelectedPath)) { var selectedDirectoryPath = fdb.SelectedPath; foreach (var selectedProject in selectedProjects) { if (!managers.Contains(selectedProject.Manager)) { continue; } var targetDirectoryPath = Path.Combine(selectedDirectoryPath, selectedProject.Id.ToString().Replace("-", string.Empty)); this.Container.Resolve <IFileManagerService>().CreateDirectoryPathIfNotExists(targetDirectoryPath); eventServiceClient.CopyProjectAttachmentsRequest(selectedProject.Manager.Id, selectedProject.Id, targetDirectoryPath); } messageService.ShowOkMessageDialog("Info", $"Started copy proccess to: {selectedDirectoryPath}"); } } } } }, () => SelectedItem != null); this.SelectedLookupChanged += lookup => CopyAttachmentsCommand.RaiseCanExecuteChanged(); }
/// <summary> /// Updates the selection for an item based on user interaction. /// </summary> /// <param name="index">The index of the item.</param> /// <param name="select">Whether the item should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> /// <param name="rightButton">Whether the event is a right-click.</param> protected void UpdateSelection( int index, bool select = true, bool rangeModifier = false, bool toggleModifier = false, bool rightButton = false) { if (index != -1) { if (select) { var mode = SelectionMode; var multi = (mode & SelectionMode.Multiple) != 0; var toggle = (toggleModifier || (mode & SelectionMode.Toggle) != 0); var range = multi && rangeModifier; if (rightButton) { if (!_selection.Contains(index)) { UpdateSelectedItem(index); } } else if (range) { UpdateSelectedItems(() => { var start = SelectedIndex != -1 ? SelectedIndex : 0; var step = start < index ? 1 : -1; _selection.Clear(); for (var i = start; i != index; i += step) { _selection.Add(i); } _selection.Add(index); var first = Math.Min(start, index); var last = Math.Max(start, index); foreach (var container in ItemContainerGenerator.Containers) { MarkItemSelected( container.Index, container.Index >= first && container.Index <= last); } ResetSelectedItems(); }); } else if (multi && toggle) { UpdateSelectedItems(() => { if (!_selection.Contains(index)) { _selection.Add(index); MarkItemSelected(index, true); SelectedItems.Add(ElementAt(Items, index)); } else { _selection.Remove(index); MarkItemSelected(index, false); if (index == _selectedIndex) { UpdateSelectedItem(_selection.First(), false); } SelectedItems.Remove(ElementAt(Items, index)); } }); } else if (toggle) { SelectedIndex = (SelectedIndex == index) ? -1 : index; } else { UpdateSelectedItem(index); } if (Presenter?.Panel != null) { var container = ItemContainerGenerator.ContainerFromIndex(index); KeyboardNavigation.SetTabOnceActiveElement( (InputElement)Presenter.Panel, container); } } else { LostSelection(); } } }
/// <summary> /// Updates the selection for an item based on user interaction. /// </summary> /// <param name="index">The index of the item.</param> /// <param name="select">Whether the item should be selected or unselected.</param> /// <param name="rangeModifier">Whether the range modifier is enabled (i.e. shift key).</param> /// <param name="toggleModifier">Whether the toggle modifier is enabled (i.e. ctrl key).</param> protected void UpdateSelection( int index, bool select = true, bool rangeModifier = false, bool toggleModifier = false) { if (index != -1) { if (select) { var mode = SelectionMode; var toggle = toggleModifier || (mode & SelectionMode.Toggle) != 0; var multi = (mode & SelectionMode.Multiple) != 0; var range = multi && SelectedIndex != -1 && rangeModifier; if (!toggle && !range) { SelectedIndex = index; } else if (multi && range) { SynchronizeItems( SelectedItems, GetRange(Items, SelectedIndex, index)); } else { var item = ElementAt(Items, index); var i = SelectedItems.IndexOf(item); if (i != -1 && (!AlwaysSelected || SelectedItems.Count > 1)) { SelectedItems.Remove(item); } else { if (multi) { SelectedItems.Add(item); } else { SelectedIndex = index; } } } if (Presenter?.Panel != null) { var container = ItemContainerGenerator.ContainerFromIndex(index); KeyboardNavigation.SetTabOnceActiveElement( (InputElement)Presenter.Panel, container); } } else { LostSelection(); } } }
/// <summary> /// Called when the <see cref="SelectedItems"/> CollectionChanged event is raised. /// </summary> /// <param name="sender">The event sender.</param> /// <param name="e">The event args.</param> private void SelectedItemsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (_syncingSelectedItems) { return; } void Add(IList newItems, IList addedItems = null) { foreach (var item in newItems) { var index = MarkItemSelected(item, true); if (index != -1 && _selection.Add(index) && addedItems != null) { addedItems.Add(item); } } } void UpdateSelection() { if ((SelectedIndex != -1 && !_selection.Contains(SelectedIndex)) || (SelectedIndex == -1 && _selection.HasItems)) { _selectedIndex = _selection.First(); _selectedItem = ElementAt(Items, _selectedIndex); RaisePropertyChanged(SelectedIndexProperty, -1, _selectedIndex, BindingPriority.LocalValue); RaisePropertyChanged(SelectedItemProperty, null, _selectedItem, BindingPriority.LocalValue); } } IList added = null; IList removed = null; switch (e.Action) { case NotifyCollectionChangedAction.Add: { Add(e.NewItems); UpdateSelection(); added = e.NewItems; } break; case NotifyCollectionChangedAction.Remove: if (SelectedItems.Count == 0) { SelectedIndex = -1; } foreach (var item in e.OldItems) { var index = MarkItemSelected(item, false); _selection.Remove(index); } removed = e.OldItems; break; case NotifyCollectionChangedAction.Replace: throw new NotSupportedException("Replacing items in a SelectedItems collection is not supported."); case NotifyCollectionChangedAction.Move: throw new NotSupportedException("Moving items in a SelectedItems collection is not supported."); case NotifyCollectionChangedAction.Reset: { removed = new List <object>(); added = new List <object>(); foreach (var index in _selection.ToList()) { var item = ElementAt(Items, index); if (!SelectedItems.Contains(item)) { MarkItemSelected(index, false); removed.Add(item); _selection.Remove(index); } } Add(SelectedItems, added); UpdateSelection(); } break; } if (added?.Count > 0 || removed?.Count > 0) { var changed = new SelectionChangedEventArgs( SelectionChangedEvent, added ?? Empty, removed ?? Empty); RaiseEvent(changed); } }
/// <summary> /// Returns the selected list items in a array. /// </summary> /// <returns>Array with the selected items.</returns> public object[] GetSelectedItems() { object[] items = new object[SelectedItems.Count]; SelectedItems.CopyTo(items, 0); return(items); }
/// <summary> /// Updates contents of the ItemsSource when FeatureDataGrid's associated graphic collection changes. /// </summary> /// <param name="sender">Observable collection of Graphic.</param> /// <param name="e">Collection changed event arguments.</param> private void UpdateItemsSource(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) { IList newItems = e.NewItems; IList oldItems = e.OldItems; if (ItemsSource == null) { SetItemsSource(sender as ObservableCollection <Graphic>); } else { if ((ItemsSource as PagedCollectionView) != null) { object currentItem = (ItemsSource as PagedCollectionView).CurrentItem; if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset) { var features = (from object a in ItemsSource select DataSourceCreator.GetGraphicSibling(a)); newItems = (sender as ObservableCollection <Graphic>).Except(features).ToList(); oldItems = features.Except(sender as ObservableCollection <Graphic>).ToList(); } if (newItems != null && newItems.Count > 0) // New item(s) added { bool shouldResetItemsSource = false; IEnumerator enumItemsSource = ItemsSource.GetEnumerator(); if (enumItemsSource != null) { if (enumItemsSource.MoveNext()) { if (!AllAttributesMatch(enumItemsSource.Current.GetType().GetProperties(), (newItems[0] as Graphic).Attributes)) { shouldResetItemsSource = true; } } else { shouldResetItemsSource = true; } } if (shouldResetItemsSource) { UnregisterGraphicCollectionEventHandlers(); SetItemsSource(sender as ObservableCollection <Graphic>); IEnumerator enumAddedGraphics = newItems.GetEnumerator(); while (enumAddedGraphics.MoveNext()) { Graphic graphic = enumAddedGraphics.Current as Graphic; if (graphic != null) { graphic.AttributeValueChanged += Graphic_AttributeValueChanged; } } } else { IEnumerator enumAddedGraphics = newItems.GetEnumerator(); List <Graphic> selected = GraphicsLayer.SelectedGraphics.ToList(); while (enumAddedGraphics.MoveNext()) { Graphic graphic = enumAddedGraphics.Current as Graphic; if (graphic != null) { if (graphic.Selected) { selected.Add(graphic); } ItemsSource.AddToDataSource(featureLayerInfo, graphic, objectType); graphic.AttributeValueChanged += Graphic_AttributeValueChanged; } } RestorePreviousSelection(selected); } } if (oldItems != null && oldItems.Count > 0) // Item(s) removed { int selCount = SelectedItems.Count; // In Silverlight removing a graphic from the GraphicsCollection causes to lose current // selection in both GraphicsLayer and the FeatureDataGrid. // Preserving selected items in the FeatureDataGrid: List <Graphic> selItems = new List <Graphic>(selCount); for (int i = 0; i < selCount; i++) { var row = SelectedItems[i]; var graphic = DataSourceCreator.GetGraphicSibling(row); selItems.Add(graphic); } IEnumerator enumRemovedGraphics = oldItems.GetEnumerator(); while (enumRemovedGraphics.MoveNext()) { Graphic graphic = enumRemovedGraphics.Current as Graphic; int idxInItemsSource = GetRowIndexInItemsSource(graphic); if (graphic != null && idxInItemsSource > -1) { if (graphic != null) { selItems.Remove(graphic); } ItemsSource.RemoveFromDataSource(idxInItemsSource, objectType); // RemoveFromDataSource() method causes first item in the ItemsSource to be selected when there were no // items selected in the data grid. We should avoid this selection by removing it from the selection: if (selCount == 0 && SelectedItems.Count == 1) { SelectedItems.Clear(); } graphic.AttributeValueChanged -= Graphic_AttributeValueChanged; SelectedGraphics.Remove(graphic); } } RestorePreviousSelection(selItems); } } else { // If exiting ItemsSource is not a PagedCollectionView then it was empty before // just populate it with everything in GraphicsLayer. SetItemsSource((GraphicsLayer != null && GraphicsLayer.Graphics != null) ? (IList <Graphic>)GraphicsLayer.Graphics : new List <Graphic>()); } } ShowNumberOfRecords(); }
/// <summary> /// The workhorse to expand a threaded listview item /// </summary> /// <param name="lvItem"></param> /// <param name="activate">true, if lvItem should be activated</param> internal void ExpandListViewItem(ThreadedListViewItem lvItem, bool activate) { int selIdxsCount = SelectedIndices.Count; var selIdxs = new int[selIdxsCount]; SelectedIndices.CopyTo(selIdxs, 0); ThreadedListViewItem[] newItems; if (lvItem != null && lvItem.Collapsed) { if (RaiseBeforeExpandEventCancel(lvItem)) { lvItem.StateImageIndex = 0; // switch to non-state image (no +/-) return; } int paramItemIndex = lvItem.Index; int currentIndent = lvItem.IndentLevel; // if (base.SelectedItems.Count > 0 && activate) // selectedItemIndex = paramItemIndex; newItems = RaiseExpandEvent(lvItem); if (newItems == null) { ThreadedListViewItem item = _noChildsPlaceHolder; if (item == null) { item = new ThreadedListViewItemPlaceHolder(SR.FeedListNoChildsMessage) { Font = new Font(Font.FontFamily, Font.Size, FontStyle.Regular) }; } newItems = new[] { item }; } if (newItems.Length > 1 && ListViewItemSorter != null) { // sort new child entries according to listview sortorder Array.Sort(newItems, ListViewItemSorter); } if (_showInGroups) { APIEnableGrouping(false); } BeginUpdate(); try { lvItem.SetThreadState(true); lock (Items) { foreach (var newListItem in newItems) { // check, if we have all subitems for correct grouping while (newListItem.SubItems.Count < Columns.Count) { newListItem.SubItems.Add(String.Empty); } newListItem.Parent = lvItem; Items.Insert(paramItemIndex + 1, newListItem); newListItem.IndentLevel = currentIndent + 1; paramItemIndex++; } } } finally { EndUpdate(); } RedrawItems(); if (_showInGroups) { APIEnableGrouping(true); } // Make the last inserted subfolder visible, then the parent folder visible, // per default treeview behavior. try { EnsureVisible(paramItemIndex - 1); EnsureVisible(lvItem.Index); } catch (Exception ex) { _log.Error("EnsureVisible() failed", ex); } if (activate) { SelectedItems.Clear(); lvItem.Selected = true; lvItem.Focused = true; } else if (selIdxsCount > 0) { // foreach (int i in selIdxs) { // this.Items[i].Selected = true; // } } RaiseAfterExpandEvent(lvItem, newItems); } }
protected virtual void BeforeQueryStatus(OleMenuCommand command, SelectedItems selection) { //nop }
private bool MessagesDeleteCanExecute() { return(SelectedItems.Count > 0 && SelectedItems.All(x => x.CanBeDeletedForAllUsers || x.CanBeDeletedOnlyForSelf)); }
public override void RemoveBookmarks() { var bms = SelectedItems.Select(a => a.Bookmark).ToArray(); bookmarksService.Value.Remove(bms); }
private bool CanChange() { return(SelectedItems.Count() == 1 && IsDelEnable && IsEditEnable && IsNewEnable); }
/// <summary> /// Provides different key shortcuts /// </summary> /// <param name="key"></param> public void KeyDown(VirtualKey key) { switch (key) { case VirtualKey.Left: NavigateBack.ExecuteWhen(); break; case VirtualKey.Right: NavigateForward.ExecuteWhen(); break; case VirtualKey.Back: NavigateBack.ExecuteWhen(); break; case VirtualKey.F5: Refresh(); break; case VirtualKey.F2: RenameStorageItemSelectedAsync(); break; case VirtualKey.Delete: DeleteStorageItemSelected(); break; } var ctrlDown = Window.Current.CoreWindow.GetKeyState(VirtualKey.Control).HasFlag(CoreVirtualKeyStates.Down); if (!ctrlDown) { return; } switch (key) { case VirtualKey.R: Refresh(); break; case VirtualKey.C: CopyStorageItemSelected(); break; case VirtualKey.X: CutStorageItemSelected(); break; case VirtualKey.V: PasteStorageItemSelected(); break; case VirtualKey.A: if (SelectedItems.Count == FileSystemElements.Count) { SelectedItems.Clear(); } else { for (int i = 0; i < FileSystemElements.Count; i++) { if (!SelectedItems.Contains(FileSystemElements[i])) { SelectedItems.Add(FileSystemElements[i]); } } } break; } }
public void ClearSelection() { SelectedItems.Clear(); }
private async Task SelectAll() { SelectedItems.AddRange(Items); await TriggerSelectedItemChanged(); }
bool CanEditUserRole() { return(SelectedItems.Any()); }
public SelectedProjectItemsNodeFactory(SelectedItems items) { _items = items; }
private async void TokenizingTextBox_CharacterReceived(UIElement sender, CharacterReceivedRoutedEventArgs args) { var container = ContainerFromItem(_currentTextEdit) as TokenizingTextBoxItem; if (container != null && !(GetFocusedElement().Equals(container._autoSuggestTextBox) || char.IsControl(args.Character))) { if (SelectedItems.Count > 0) { var index = _innerItemsSource.IndexOf(SelectedItems.First()); await RemoveAllSelectedTokens(); // Wait for removal of old items _ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // If we're before the last textbox and it's empty, redirect focus to that one instead if (index == _innerItemsSource.Count - 1 && string.IsNullOrWhiteSpace(_lastTextEdit.Text)) { var lastContainer = ContainerFromItem(_lastTextEdit) as TokenizingTextBoxItem; lastContainer.UseCharacterAsUser = true; // Make sure we trigger a refresh of suggested items. _lastTextEdit.Text = string.Empty + args.Character; UpdateCurrentTextEdit(_lastTextEdit); lastContainer._autoSuggestTextBox.SelectionStart = 1; // Set position to after our new character inserted lastContainer._autoSuggestTextBox.Focus(FocusState.Keyboard); } else { //// Otherwise, create a new textbox for this text. UpdateCurrentTextEdit(new PretokenStringContainer((string.Empty + args.Character).Trim())); // Trim so that 'space' isn't inserted and can be used to insert a new box. _innerItemsSource.Insert(index, _currentTextEdit); // Need to wait for containerization _ = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { var newContainer = ContainerFromIndex(index) as TokenizingTextBoxItem; // Should be our last text box newContainer.UseCharacterAsUser = true; // Make sure we trigger a refresh of suggested items. void WaitForLoad(object s, RoutedEventArgs eargs) { if (newContainer._autoSuggestTextBox != null) { newContainer._autoSuggestTextBox.SelectionStart = 1; // Set position to after our new character inserted newContainer._autoSuggestTextBox.Focus(FocusState.Keyboard); } newContainer.Loaded -= WaitForLoad; } newContainer.AutoSuggestTextBoxLoaded += WaitForLoad; }); } }); } else { // TODO: It looks like we're setting selection and focus together on items? Not sure if that's what we want... // If that's the case, don't think this code will ever be called? //// TODO: Behavior question: if no items selected (just focus) does it just go to our last active textbox? //// Community voted that typing in the end box made sense if (_innerItemsSource[_innerItemsSource.Count - 1] is ITokenStringContainer textToken) { var last = ContainerFromIndex(Items.Count - 1) as TokenizingTextBoxItem; // Should be our last text box var position = last._autoSuggestTextBox.SelectionStart; textToken.Text = last._autoSuggestTextBox.Text.Substring(0, position) + args.Character + last._autoSuggestTextBox.Text.Substring(position); last._autoSuggestTextBox.SelectionStart = position + 1; // Set position to after our new character inserted last._autoSuggestTextBox.Focus(FocusState.Keyboard); } } } }
public void UnselectAll() { SelectedItems.Clear(); }
/// <summary> /// 获得 当前行是否被选中 /// </summary> /// <param name="item"></param> /// <returns></returns> protected CheckboxState RowCheckState(TItem item) => SelectedItems.Contains(item) ? CheckboxState.Checked : CheckboxState.UnChecked;
protected override void Invoke(OleMenuCommand command, SelectedItems selection) { var activeDocument = dte.ActiveDocument; Invoke(activeDocument); }
private async Task Clear() { SelectedItems.Clear(); await TriggerSelectedItemChanged(); }
/// <summary> /// Clears the SelectedItems that are being dragged /// </summary> private void ResetDragItems() { _ItemsToMove.Clear(); SelectedItems.Clear(); }
private bool GetCheckedState(SelectedItem item) => SelectedItems.Contains(item);
private void SetIgnoreMenuItemState(OleMenuCommand menuCommand, SelectedItems selections) { if (menuCommand.Visible) { var projectItem = selections.Item(1).ProjectItem; var settings = this.VisualStudioJSLintProvider.LoadSettings(projectItem.ContainingProject); var ignored = settings.NormalizeIgnore(); var ignoreState = projectItem.Access().IgnoreState(ignored); menuCommand.Checked = ignoreState != ProjectItemIgnoreState.None; menuCommand.Enabled = ignoreState != ProjectItemIgnoreState.Implicit; } }