D.H.
D.H.

Reputation: 1093

How do I allow a ComboBox to have a selected value that is not in ItemsSource?

I have a ComboBox like this:

<ComboBox IsEditable="True" 
          ItemsSource="{Binding SelectableValues}"
          SelectedValue="{Binding SelectedValue}" />

SelectableValues is a list of double and SelectedValue is a double. If the user chooses a value from the list or manually enters one of those values, my SelectedValue property is updated. But if the user manually enters another value, it isn't. How do I allow SelectedValue to take other values than those in ItemsSource?

Edit: Think of it like the font size box in MS Word. I can choose a value from the list, or provide my own value.

Upvotes: 2

Views: 1642

Answers (1)

RockWorld
RockWorld

Reputation: 1288

Create a user control inheriting comboBox. Add a dependency property as 'SelectedText'. create event handler for LostFocus on combo box, in event handler assign the entered value dependency property 'SelectedText'. do binding on 'SelectedText', in its setter if value is new then ad to collection and set SelectedValue to new one.

Indirectly you have to update source by adding new property in ComboBox.


  public class ExtendedComboBox : ComboBox
    {
        public ExtendedComboBox()
        {
            this.IsEditable = true;
            this.LostFocus += ComboBox_LostFocus;
        }
        public string SelectedText
        {
            get
            {
                return (string)GetValue(SelectedTextProperty);
            }
            set
            {
                SetValue(SelectedTextProperty, value);
            }
        }

        public static readonly DependencyProperty SelectedTextProperty = DependencyProperty.Register("SelectedText", typeof(string), typeof(ExtendedComboBox), new FrameworkPropertyMetadata(string.Empty, new PropertyChangedCallback(OnSelectedTextPropertyChanged)));


        private static void OnSelectedTextPropertyChanged(object sender, DependencyPropertyChangedEventArgs e)
        {

        }

        private void ComboBox_LostFocus(object sender, RoutedEventArgs e)
        {
            SelectedText = (e.Source as ComboBox).Text??string.Empty;
        }

    }

   // Binding Example

 %gt%local:ExtendedComboBox Margin="3" x:Name="ecb" SelectedText="{Binding SelectedText,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" ItemsSource="{Binding SelectedTextList}">%gt/local:ExtendedComboBox>


Upvotes: 1

Related Questions