aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Tango.SharedUI/Controls/SearchComboBox.cs
blob: f9d65bd2b18a22d9aa12f73f483ee6e3541262ca (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
using System;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;

namespace Tango.SharedUI.Controls
{
    [TemplatePart(Name = SearchComboBox.PartEditor, Type = typeof(System.Windows.Controls.TextBox))]
    [TemplatePart(Name = SearchComboBox.PartPopup, Type = typeof(Popup))]
    public class SearchComboBox : ComboBox
    {
        public const string PartEditor = "Search";
        public const string PartPopup = "PART_Popup";
        private int _savedSelectedIndex = -1;
        private bool _editorMouseLeaveFlag = false;

        #region Properties

        private TextBox _editor;

        public TextBox Editor
        {
            get { return _editor; }
            set { _editor = value; }
        }


        private Popup _popup;

        public Popup Popup
        {
            get { return _popup; }
            set { _popup = value; }
        }

        private DispatcherTimer _fetchTimer;

        public DispatcherTimer FetchTimer
        {
            get { return _fetchTimer; }
            set { _fetchTimer = value; }
        }
        

        private string _searchText = "";
        /// <summary>
        /// Gets or sets the search text of TextBox.
        /// </summary>
        public string SearchText
        {
            get { return _searchText; }
            set
            {
                if(_searchText != value && value != null)
                {
                    _searchText = value;
                }
                
            }
        }

        public ListCollectionView SearchItemsList
        {
            get { return (ListCollectionView)GetValue(SearchItemsListProperty); }
            set { SetValue(SearchItemsListProperty, value); }
        }
        /// <summary>
        /// The search items list property for popup items list
        /// </summary>
        public static readonly DependencyProperty SearchItemsListProperty =
            DependencyProperty.Register("SearchItemsList", typeof(ListCollectionView), typeof(SearchComboBox), new PropertyMetadata(default(ObservableCollection<string>)));


        public string SearchParam
        {
            get { return (string)GetValue(SearchParamProperty); }
            set { SetValue(SearchParamProperty, value); }
        }

        public static readonly DependencyProperty SearchParamProperty =
            DependencyProperty.Register("SearchParam", typeof(string), typeof(SearchComboBox), new FrameworkPropertyMetadata(""));

        public System.Collections.IList SourceItems
        {
            get { return (System.Collections.IList)GetValue(SourceItemsProperty); }
            set { SetValue(SourceItemsProperty, value);  }
        }

        public static readonly DependencyProperty SourceItemsProperty =
            DependencyProperty.Register("SourceItems", typeof(System.Collections.IList), typeof(SearchComboBox), new PropertyMetadata(default(System.Collections.IList)));


        #endregion

        
        #region Constructors

        static SearchComboBox()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(SearchComboBox), new FrameworkPropertyMetadata(typeof(SearchComboBox)));
        }

        public SearchComboBox()
        {
            
        }
        
        #endregion //Constructors

        #region override
        protected override void OnLostMouseCapture(MouseEventArgs e)
        {
            if (Mouse.Captured == null)
            {
                if (e.OriginalSource == this)
                {
                    //SetPopupState();
                }
                else if (IsDropDownOpen)
                {
                    Mouse.Capture(this, CaptureMode.SubTree);
                }
            }

            base.OnLostMouseCapture(e);
        }

        /// <summary>
        /// Responds to a <see cref="T:System.Windows.Controls.ComboBox" /> selection change by raising a <see cref="E:System.Windows.Controls.Primitives.Selector.SelectionChanged" /> event.
        /// Change selection only on click on item
        /// </summary>
        /// <param name="e">Provides data for <see cref="T:System.Windows.Controls.SelectionChangedEventArgs" />.</param>
        protected override void OnSelectionChanged(SelectionChangedEventArgs e)
        {
            if (Editor == null || !Editor.IsKeyboardFocused || ( Editor.IsKeyboardFocused && _editorMouseLeaveFlag ) )
            {
                base.OnSelectionChanged(e);
                if (e.AddedItems.Count != 0 && SelectedIndex != this.SourceItems.IndexOf(e.AddedItems[0]))
                {
                        SelectedValue = e.AddedItems[0];
                }
            }
            e.Handled = true;
        }

       
        #endregion

        #region Initialization

        void InitSelectedList()
        {
            if (SearchItemsList == null)
            {
                SearchItemsList = new ListCollectionView(this.SourceItems);
                if (String.IsNullOrEmpty(SearchParam))
                    SearchItemsList.Filter = null;
                else
                {
                    SearchItemsList.Filter = (ob) =>
                    {
                        var prop = ob.GetType().GetProperty(SearchParam);
                        if (prop == null)
                        {
                            return true;
                        }
                        string value = prop.GetValue(ob, null) as string;
                        return value != null && (String.IsNullOrEmpty(SearchText) || value.ToLower().Contains(SearchText.ToLower()));
                    };
                }
                Binding mbinding = new Binding("SearchItems");
                mbinding.Mode = BindingMode.Default;
                mbinding.Source = this;
                mbinding.Path = new PropertyPath("SearchItemsList");
               
                SetBinding(ComboBox.ItemsSourceProperty, mbinding);
            }
        }
        /// <summary>
        /// When overridden in a derived class, is invoked whenever application code or internal processes call <see cref="M:System.Windows.FrameworkElement.ApplyTemplate" />.
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
           
            var binding1 = BindingOperations.GetBinding(this, ComboBox.ItemsSourceProperty);
            SetBinding(SearchComboBox.SourceItemsProperty, binding1);
            Popup = Template.FindName(PartPopup, this) as Popup;
           
            if (Popup != null)
            {
                Popup.StaysOpen = false;
                Popup.Opened += OnPopupOpened;
                Popup.Closed += OnPopupClosed;
                
            }
            Editor = Template.FindName(PartEditor, this) as TextBox;
            if(Editor != null)
            {
                Editor.TextChanged += OnEditorTextChanged;
                Editor.MouseLeave += Editor_MouseLeave;
                Editor.MouseEnter += Editor_MouseEnter;
            }
        }

        #endregion

        #region EventHandlers
        
        private void Popup_KeyDown(object sender, KeyEventArgs e)
        {
            if (Editor != null )
            {
                Editor.Focus();
                Keyboard.Focus(Editor);
            }
        }

        private void OnPopupOpened(object sender, EventArgs e)
        {
            SearchText = "";
            InitSelectedList();
            if (Editor != null )
            {
                Editor.Text = "";
                Editor.Focus();
                Editor.SelectionStart = 0;
                Keyboard.Focus(Editor);
            }
            _savedSelectedIndex = SelectedIndex;
        }

        /// <summary>
        /// Called when [popup closed].
        ///  Selection Index/Value will be set according to unfiltered whole list
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        private void OnPopupClosed(object sender, EventArgs e)
        {
           if(SelectedIndex == -1 && _savedSelectedIndex >=0)// selection item was set to null for filtering but not selected, return to prev value
            {
                SearchText = "";
                SearchItemsList.Refresh();
                SelectedValue = SearchItemsList.GetItemAt(_savedSelectedIndex);
            }
           if(this.SourceItems.Count != SearchItemsList.Count)//selection was changed on filtered list - replace to real selection index 
            {
                var selvalue = SelectedValue;
                SearchText = "";
                SearchItemsList.Refresh();
                SelectedValue = selvalue;
            }
            _savedSelectedIndex = -1;
        }

        private void OnEditorTextChanged(object sender, TextChangedEventArgs e)
        {
            if (FetchTimer == null)
            {
                FetchTimer = new DispatcherTimer();
                FetchTimer.Interval = TimeSpan.FromMilliseconds(100);
                FetchTimer.Tick += OnFetchTimerTick;
            }
           
            FetchTimer.IsEnabled = true;
            FetchTimer.Start();
        }
        
        private void Editor_MouseEnter(object sender, MouseEventArgs e)
        {
            _editorMouseLeaveFlag = false;
        }

        private void Editor_MouseLeave(object sender, MouseEventArgs e)
        {
            _editorMouseLeaveFlag = true;
        }
        
        private void OnFetchTimerTick(object sender, EventArgs e)
        {
            FetchTimer.IsEnabled = false;
            FetchTimer.Stop();
            SearchText = Editor.Text;
            OnTextChanged();
        }

        public virtual void OnTextChanged()
        {
           if (SearchItemsList != null)
            {
                SearchItemsList.Refresh();
            }
           if(SearchItemsList.Count > 0 && SelectedIndex != -1)
            {
                SelectedIndex = -1;// trick: all filtered items are displayed only with SelectedIndex = -1 , otherwise it is displayed 1 less 
            }
        }

        #endregion
    }
}