1
votes

I have a problem with some binding, I have ObservableCollection of strings with all my combobox dropdown items. It should be possible to either select a value from the dropdown menu or insert some text manually or combine both methods.

<ComboBox ItemsSource="{Binding AvailableAddressSymbols}" 
    Text="{Binding SelectedItem.LowerBound,
        ElementName=combobox_sys_data_protection}"
    HorizontalAlignment="Right" 
    IsEditable="True"
    DropDownOpened="SymbolAddressRefress_Dropdownopend" />
<ComboBox ItemsSource="{Binding AvailableAddressSymbols}" 
    Text="{Binding SelectedItem.UpperBound,
        ElementName=combobox_sys_code_protection}"
    IsEditable="True"
    DropDownOpened="SymbolAddressRefress_Dropdownopend" />

I'm binding to the text property of that combobox to allow manually written text. Everything works fine, but I have more than one of these comboboxes. The available Items for the combobox get refreshed on drop down opened.

Now here comes the problem: When I select a value in combobox1 and I want to select a value in combobox2 then the vaule from combobox1 is set to " ";

The refresh clears the itemlist and adds the new values, I think here is the problem but I need to refresh it because there will maybe new values.

    internal void refreshAvailableAddressSymbols()
    {
        AvailableAddressSymbols.Clear();
        for (int i = 0; 
             i < Database.ProjectConfiguration.AddressSymbols.Count;
             i++)
        {
          AvailableAddressSymbols.Add(
            Database.ProjectConfiguration
                .AddressSymbols[i].StartAddress);
          AvailableAddressSymbols.Add(
            Database.ProjectConfiguration
               .AddressSymbols[i].EndAddress);
        }
    }
1

1 Answers

1
votes

Some background:

With a ComboBox in WPF the SelectedItem must be one of the dropdown-Items all the time.

This means: In the moment you Clear() the ObservalCollection bound to ItemsSource the condition above no longer holds and ComboBox clears SelecetdItem.

To avoid this, there are two strategies:

  1. Remember your selected item in a local variable, Clear your items, set items to a new set ans then set SelectedItem to an item now available in the dropdown list.

  2. Do not Clear() your itmes but update the list (adding new, removing old elemnnts). As long as you don't remove the SelectedItemeverything works fine