Geeks With Blogs
Nat Luengnaruemitchai Geek Blog

Sometimes, you would like to get a combobox where a user can type. This can be done by turning on IsEditable property to true. However, it opens another can of worm, it means the user can type anything in the combobox even text that is not in the ItemsSource.

To provide LimitToList feature, you can hook up an event to PreviewLostKeyboardFocus as follows:

 

        private void ComboBox_PreviewLostKeyboardFocus(object sender, KeyboardFocusChangedEventArgs e)

        {

            if (!e.Handled)

            {

                TextBox textBox = e.OldFocus as TextBox;

                ComboBox comboBox = sender as ComboBox;

                if (textBox != null && comboBox!=null)

                {

                    DependencyObject common = comboBox.FindCommonVisualAncestor(e.NewFocus as DependencyObject);

                    // validate only the case when user step out of this control

                    if (common != comboBox)

                    {

                        bool invalid = !string.IsNullOrEmpty(textBox.Text) && comboBox.SelectedIndex < 0;

                        if (invalid)

                        {

                            e.Handled = true;

                        }

                    }

                }

            }

        }

Later, I will show you how to create a visual clue to indicate that the combobox is invalid

Posted on Tuesday, August 7, 2007 8:37 PM WPF | Back to top


Comments on this post: WPF ComboBox with LimitToList feature: Part I

# re: WPF ComboBox with LimitToList feature: Part I
Requesting Gravatar...
Hello ,

I am wondering how others are adding default item to Combox box. I am binding my items to combox from ItemSource which is assinged a list of objects. But the problem is how can i add default text like " Select .." on top of the items that are there in the collection. So users can deselect the previous selection.

I dont want to do foreach and add items as i will end up duplicating code every time I have to use a combo box. How are you dealing with this problem? Any suggestions..

Thanks,
Raj
Left by How can we add default item Text on Sep 29, 2007 6:14 PM

# re: WPF ComboBox with LimitToList feature: Part I
Requesting Gravatar...
even iam facing the same problem can anybody please help
me
thanks in advance
raj
Left by raj on Jul 02, 2009 1:38 AM

# Mr.
Requesting Gravatar...
This is really illustrative station for all the visitors. Typically this typewrite of transfer are not free. Zealous labor you soul finished for all of us.

bipolar disorder treatment
Left by bipolar disorder treatment on Jul 22, 2011 5:12 AM

Your comment:
 (will show your gravatar)


Copyright © Nat Luengnaruemitchai | Powered by: GeeksWithBlogs.net