博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
wpf 自动完成comboxBox
阅读量:5901 次
发布时间:2019-06-19

本文共 11907 字,大约阅读时间需要 39 分钟。

样式:

View Code
M 0 0 L 3.5 4 L 7 0 Z

 

三个属性注意

this.StaysOpenOnEdit = true 

this.IsEditable = true

this.IsTextSearchEnabled = false//自带的自动完成

 

 

第一种:简单的。

View Code
using System;using System.Collections.Generic;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Controls;using System.Windows.Input;namespace GEMS.Windows.Controls.CustomControls{    public class SimpleAutoCompleteComboBox : ComboBox    {        static SimpleAutoCompleteComboBox()        {            DefaultStyleKeyProperty.OverrideMetadata(typeof(SimpleAutoCompleteComboBox), new FrameworkPropertyMetadata(typeof(SimpleAutoCompleteComboBox)));        }        public SimpleAutoCompleteComboBox()        {            this.StaysOpenOnEdit = true;            this.IsEditable = true;            this.IsTextSearchEnabled = true;            this.LostFocus += SimpleAutoCompleteComboBox_LostFocus;        }        public override void OnApplyTemplate()        {            base.OnApplyTemplate();            //load the text box control            if (this.EditableTextBox != null)            {               // this.EditableTextBox.PreviewKeyDown += new KeyEventHandler(EditableTextBox_PreviewKeyDown);                this.EditableTextBox.TextChanged += new TextChangedEventHandler(EditableTextBox_TextChanged);            }        }        //void EditableTextBox_PreviewKeyDown(object sender, KeyEventArgs e)        //{        //    this.IsKeyEvent = true;        //}        void EditableTextBox_TextChanged(object sender, TextChangedEventArgs e)        {            if ( this.EditableTextBox.IsFocused)                        {                this.IsDropDownOpen = true;            }                   }        ///         /// Gets the text box in charge of the editable portion of the combo box.        ///         protected TextBox EditableTextBox        {            get            {                return base.GetTemplateChild("PART_EditableTextBox") as TextBox;            }        }        private string SelectedText        {            get            {                if (this.SelectedIndex == -1) return string.Empty;                return this.SelectedItem.GetType().GetProperty(this.DisplayMemberPath).GetValue(this.SelectedItem, null).ToString();            }        }        void SimpleAutoCompleteComboBox_LostFocus(object sender, RoutedEventArgs e)        {            this.IsDropDownOpen = false;            // to prevent misunderstanding that user has entered some information            if (this.SelectedIndex == -1)            {                this.Text = null;                this.SelectedItem = null;                this.SelectedValue = null;            }            // syncronize text            else                this.Text = this.SelectedText;            // release timer resources                       try            {                this.EditableTextBox.CaretIndex = 0;            }            catch { }        }    }}

 

第2种:下拉只显示关联的

View Code
using System;using System.Collections;using System.Collections.Generic;using System.Collections.ObjectModel;using System.ComponentModel;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Timers;using System.Windows;using System.Windows.Controls;using System.Windows.Input;namespace GEMS.Windows.Controls.CustomControls{    public class AutoCompleteComboBox : ComboBox    {        #region Fields        private Timer _interval;        private int _maxRecords = 10;        private bool _typeAhead = false;        private bool IsKeyEvent = false;        private bool _clearOnEmpty = true;        private int _delay = DEFAULT_DELAY;        private const int DEFAULT_DELAY = 500;        private ObservableCollection
CurrentItems; #endregion #region properties [DefaultValue(DEFAULT_DELAY)] public int Delay { get { return this._delay; } set { this._delay = value; } } public bool ClearOnEmpty { get { return this._clearOnEmpty; } set { this._clearOnEmpty = true; } } ///
/// Gets the text box in charge of the editable portion of the combo box. /// protected TextBox EditableTextBox { get { return base.GetTemplateChild("PART_EditableTextBox") as TextBox; } } private string SelectedText { get { if (this.SelectedIndex == -1) return string.Empty; return this.SelectedItem.GetType().GetProperty((string.IsNullOrWhiteSpace(this.SearchBy) ? this.DisplayMemberPath : this.SearchBy)).GetValue(this.SelectedItem, null).ToString(); } } #endregion #region DependencyProperty public static readonly DependencyProperty DataSourceProperty = DependencyProperty.Register("DataSource", typeof(IEnumerable), typeof(AutoCompleteComboBox), new PropertyMetadata(null, new PropertyChangedCallback(OnDataSourceChanged))); private static void OnDataSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { AutoCompleteComboBox autoCompleteComboBox = (AutoCompleteComboBox)d; autoCompleteComboBox.ItemsSource = (IEnumerable)e.NewValue; } public IEnumerable DataSource { get { return base.GetValue(AutoCompleteComboBox.DataSourceProperty) as IEnumerable; } set { base.SetValue(AutoCompleteComboBox.DataSourceProperty, value); } } public string SearchBy { get { return (string)GetValue(SearchByProperty); } set { SetValue(SearchByProperty, value); } } // Using a DependencyProperty as the backing store for SearchBy. This enables animation, styling, binding, etc... public static readonly DependencyProperty SearchByProperty = DependencyProperty.Register("SearchBy", typeof(string), typeof(AutoCompleteComboBox), new PropertyMetadata(null)); #endregion public override void OnApplyTemplate() { base.OnApplyTemplate(); //load the text box control if (this.EditableTextBox != null) { this.EditableTextBox.PreviewKeyDown += new KeyEventHandler(EditableTextBox_PreviewKeyDown); this.EditableTextBox.TextChanged += new TextChangedEventHandler(EditableTextBox_TextChanged); } } static AutoCompleteComboBox() { DefaultStyleKeyProperty.OverrideMetadata(typeof(AutoCompleteComboBox), new FrameworkPropertyMetadata(typeof(AutoCompleteComboBox))); } public AutoCompleteComboBox() { CurrentItems = new ObservableCollection
(); if (!DesignerProperties.GetIsInDesignMode(this)) { this._interval = new Timer(this.Delay); this._interval.AutoReset = true; this._interval.Elapsed += new ElapsedEventHandler(_interval_Elapsed); } this.Loaded += AutoCompleteComboBox_Loaded; this.LostFocus += AutoCompleteComboBox_LostFocus; this.SelectionChanged += AutoCompleteComboBox_SelectionChanged; this.StaysOpenOnEdit = true; this.IsEditable = true; this.IsTextSearchEnabled = false; } private void AutoCompleteComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e) { this._interval.Stop(); } void AutoCompleteComboBox_LostFocus(object sender, RoutedEventArgs e) { this.IsKeyEvent = false; this.IsDropDownOpen = false; // to prevent misunderstanding that user has entered some information if (this.SelectedIndex == -1) { this.Text = null; this.SelectedItem = null; this.SelectedValue = null; } // syncronize text else this.Text = this.SelectedText; // release timer resources this._interval.Close(); try { this.EditableTextBox.CaretIndex = 0; } catch { } } void AutoCompleteComboBox_Loaded(object sender, RoutedEventArgs e) { this.ItemsSource = this.DataSource; } #region MyRegion void _interval_Elapsed(object sender, ElapsedEventArgs e) { IsKeyEvent = false; // pause the timer this._interval.Stop(); // show the drop down when user starts typing then stops this.Dispatcher.BeginInvoke((Action)delegate { // load from event source this.CurrentItems = new ObservableCollection
(); if (this.Text.Length >= 0) { foreach (var entry in DataSource) { string SearchName = entry.GetType().GetProperty((string.IsNullOrWhiteSpace(this.SearchBy) ? this.DisplayMemberPath : this.SearchBy)).GetValue(entry, null).ToString().ToUpper(); if (SearchName.StartsWith(this.Text.ToUpper(), StringComparison.CurrentCultureIgnoreCase)) { CurrentItems.Add(entry); } } this.ItemsSource = CurrentItems; this.IsDropDownOpen = this.HasItems; } else { this.IsDropDownOpen = false; } }, System.Windows.Threading.DispatcherPriority.ApplicationIdle); } #endregion #region EditableTextBoxEvent void EditableTextBox_PreviewKeyDown(object sender, KeyEventArgs e) { this.IsKeyEvent = true; } void EditableTextBox_TextChanged(object sender, TextChangedEventArgs e) { if ( this.EditableTextBox.IsFocused) { if (this.ClearOnEmpty && string.IsNullOrEmpty(this.EditableTextBox.Text.Trim())) this.ItemsSource = this.DataSource; else if (IsKeyEvent) this.ResetTimer(); } } protected void ResetTimer() { this._interval.Stop(); this._interval.Start(); } #endregion }}

 

 

转载于:https://www.cnblogs.com/FaDeKongJian/archive/2013/03/20/2971653.html

你可能感兴趣的文章
python 取整的两种方法
查看>>
POJ2406 Power Strings(KMP)
查看>>
Jmeter学习——6
查看>>
Form.elements[i]的使用
查看>>
【转载】HubbleDotNet开源全文搜索数据库项目
查看>>
django Settings cannot be imported 错误解决
查看>>
iphone开发中的数据存储:Property lists
查看>>
实战ASP.NET访问共享文件夹(含详细操作步骤)
查看>>
(转)Android Intent和PendingIntent的区别详细分析
查看>>
基于角色的访问控制rbac
查看>>
【转帖】Sql2008数据库转到sql2005
查看>>
setTimeout 和 setInterval 的区别
查看>>
WPF系列一
查看>>
新浪微博教程(二)各个类和架构说明
查看>>
PostgreSQL消息乱码的解决
查看>>
什么叫即席查询
查看>>
测试 ClownFish、CYQ、Entity Framework、Moon、MySoft、NHibernate、PDF、XCode数据访问组件性能...
查看>>
安卓开发_浅谈TimePicker(时间选择器)
查看>>
Debugging with GDB 用GDB调试多线程程序
查看>>
clang编译mysql(Ubuntu10 64位)
查看>>