Nat Luengnaruemitchai

Geek Blog

  Home  |   Contact  |   Syndication    |   Login
  99 Posts | 0 Stories | 212 Comments | 236 Trackbacks

News

Archives

Post Categories

Blogroll

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 07, 2007 8:37 PM

Feedback

# re: WPF ComboBox with LimitToList feature: Part I 9/29/2007 6:14 PM How can we add default item Text
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

# re: WPF ComboBox with LimitToList feature: Part I 7/2/2009 1:38 AM raj
even iam facing the same problem can anybody please help
me
thanks in advance
raj

Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: