views:

33

answers:

1

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.

A: 

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>


Rakesh Gunijan
I don't actually want to add anything to the list. I want it to work like the font size box in e.g. Word. I can choose one of the values in the list, or I can provide my own value, that will then be used (but not added to the list).
D.H.
Ok then in that case dont add value into collection. Anyway you can use it directly. Make sense??
Rakesh Gunijan
Basically Combobox has a text property which is not a dependency property. So you have to create a dependency property to extract the enetered text. It can be achieved by subscribing to lostfocus event.
Rakesh Gunijan