public MyMenuItem Add(MyMenuItem item) { base.Add(item); item.Click += (e) => ItemClicked?.Invoke(item); MenuItemAdded?.Invoke(item); return(item); }
/// <summary> /// Updates the suggestions for the current word or all text whenever /// the text changes. Opens the suggestions if they don't exist. /// </summary> private void RefreshSuggestions() { //Clears all old suggestions. gui.suggestions.Items.Clear(); //Builds a list of all suggested items. var filteredSuggestions = new List <Tuple <string, string> >(); var otherSuggestions = new List <Tuple <string, string> >(); int suggestionsAllowed = 10; //Adds each suggestion up to the max allowed. string userText = String.Empty; if ((!searchByWord || gui.textbox.Text == string.Empty)) { userText = RemoveDiacritics(gui.textbox.Text.ToLower()); } else { var words = gui.textbox.Text.Split(' '); userText = RemoveDiacritics(words[words.Length - 1].ToLower()); } //Records suggestions for StartsWith and Contains separately. for (int i = 0; i < suggestions.Count; i++) { string searchText = RemoveDiacritics(suggestions[i].Item1.ToLower()); if (searchText.StartsWith(userText)) { filteredSuggestions.Add(suggestions[i]); } else if (searchText.Contains(userText) && filteredSuggestions.Count + otherSuggestions.Count < suggestionsAllowed) { otherSuggestions.Add(suggestions[i]); } if (filteredSuggestions.Count == suggestionsAllowed) { break; } } //Adds to the filtered suggestions up to the max count. if (filteredSuggestions.Count < suggestionsAllowed) { for (int i = 0; i < otherSuggestions.Count; i++) { filteredSuggestions.Add(otherSuggestions[i]); if (filteredSuggestions.Count == suggestionsAllowed) { break; } } } //Creates a gui item for each match. Matches will //appear in sorted order since original file is sorted. for (int i = 0; i < filteredSuggestions.Count; i++) { ListBoxItem item = new ListBoxItem(); item.Content = filteredSuggestions[i].Item1; //Clicking selects the item. item.PreviewMouseLeftButtonDown += (sender, e) => { SelectSuggestion((string)item.Content); }; //Pressing enter selects the item. item.KeyDown += (sender, e) => { if (e.Key == System.Windows.Input.Key.Enter) { SelectSuggestion((string)item.Content); } }; gui.suggestions.Items.Add(item); MenuItemAdded?.Invoke(item); } //Hides or un-hides the suggestions as appropriate. if (filteredSuggestions.Count != 0 && !string.IsNullOrWhiteSpace(gui.textbox.Text)) { gui.suggestions.Visibility = System.Windows.Visibility.Visible; } else { gui.suggestions.Visibility = System.Windows.Visibility.Collapsed; } }