简体   繁体   中英

WPF Combo box filter not working on the first character WPF C#?

Basically what I have is a wpf combo box with both isTextSearchEnable and isEditable, enabled. I want to allow use to key in what they want to find and filter the combo box items to show relatable items only.

If the user keys in MP-1, it should only show items that contains with those text and not show unrelated items. So far, the code works for the 2nd character but not the first. Any ideas or what am I doing wrong here? 输入第一个字符 输入第二个字符

The code that I have so far,

public class FilterViewModel
        {
            public IEnumerable<string> DataSource { get; set; }

            public FilterViewModel()
            {
                DataSource = new[] { "MP-10001", "MP-10002", "MP-10003", "MP-10004", "XD-20001", "XD-20002", "XD-20003" };
            }
        }

        public MainWindow()
        {
            InitializeComponent();

            FilterViewModel vm = new FilterViewModel();
            this.DataContext = vm;
        }


        private void FilteredCmb_KeyUp(object sender, KeyEventArgs e)
        {
            CollectionView cv = (CollectionView)CollectionViewSource.GetDefaultView(cmbBox.ItemsSource);
            
            cv.Filter = ((o) =>
            {
                if (String.IsNullOrEmpty(cmbBox.Text)) return true;
                else
                {
                    if (((string)o).Contains(cmbBox.Text)) return true;
                    else return false;
                }
            });

            cv.Refresh();            
        }
<Grid>
        <ComboBox x:Name="cmbBox" HorizontalAlignment="Left" Margin="78,36,0,0" VerticalAlignment="Top" Width="362" IsEditable="True" IsTextSearchEnabled="True" Height="47" KeyUp="FilteredCmb_KeyUp" StaysOpenOnEdit="True" IsDropDownOpen="True" ItemsSource="{Binding DataSource}"/>

    </Grid>

The default behaviour of isTextSearchEnable="True" is selecting the first partial match and so your filter matches the entire item and returns false for all other entries. Take a look at the xaml on the question you seem to have gotten that code from: Simple WPF combobox filter

You can use AutoCompleteBox, nice control that contains advanced features of seaching and filtering, install this Package:

PM> Install-Package WPFToolkit

Here is a nice tutorial about it: https://www.broculos.net/2014/04/wpf-autocompletebox-autocomplete-text.html

for the download link it removed from codeplex, so you can find it here: https://github.com/dotnetprojects/WpfToolkit

Or xceed have a great control:

Install-Package Extended.Wpf.Toolkit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM