Advertisement
parabola949

Autocomplete ComboBox WPF with 10 item history

Dec 4th, 2013
224
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. //Will redo in MVVM later, but the quick and dirty method
  2. // In View.xaml:
  3. <ComboBox Name="NovellHistory" HorizontalAlignment="Left" Margin="50,28,0,0" VerticalAlignment="Top" Width="200" IsEditable="True">
  4.             <ComboBox.Style>
  5.                 <Style>
  6.                     <EventSetter Event="TextBox.TextChanged" Handler="History_TextChanged" />
  7.                 </Style>
  8.             </ComboBox.Style>
  9.         </ComboBox>
  10.  
  11.  
  12. // In View.cs:
  13. public NovellDesktopView()
  14.         {
  15.             InitializeComponent();
  16.             NovellHistory.ItemsSource = Settings.NovellHistory;
  17.         }
  18.  
  19.         private void Run_Click(object sender, RoutedEventArgs e)
  20.         {
  21.             var history = Settings.NovellHistory;
  22.             Settings.NovellHistory = AddHistoryItem(history, NovellHistory.Text);
  23.         }
  24.  
  25.         private List<string> AddHistoryItem(List<string> input, string item)
  26.         {
  27.             var output = new List<string>();
  28.             output.Add(item);
  29.             output.AddRange(input);
  30.             if (output.Count >= 10)
  31.                 output.RemoveAt(9);
  32.             return output;
  33.         }
  34.  
  35.         private void History_TextChanged(object sender, TextChangedEventArgs e)
  36.         {
  37.             var box = (ComboBox)sender;
  38.             box.ItemsSource = from entry in Settings.NovellHistory where entry.ToLower().Contains(box.Text.ToLower()) select entry;
  39.             box.IsDropDownOpen = true;
  40.         }
  41.  
  42. //In Settings.Designer.cs
  43.         [global::System.Configuration.UserScopedSettingAttribute()]
  44.         [global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
  45.         [global::System.Configuration.DefaultSettingValueAttribute("")]
  46.         public System.Collections.Generic.List<string> NovellHistory
  47.         {
  48.             get {
  49.                 return ((System.Collections.Generic.List<string>)(this["NovellHistory"]));
  50.             }
  51.             set {
  52.                 this["NovellHistory"] = value;
  53.             }
  54.         }
  55.  
  56. //In my Settings.cs class (because I hate typing out Properties.Settings.Default.SomeSetting)
  57.         public static List<string> NovellHistory
  58.         {
  59.             get { return Properties.Settings.Default.NovellHistory; }
  60.             set { Properties.Settings.Default.NovellHistory = value; Properties.Settings.Default.Save(); }
  61.         }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement