1
votes

I've created the UserControl DefaultComboBox:

<UserControl x:Class="MyProject.ComboBoxes.DefaultComboBox"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
    <Grid>
        <ComboBox x:Name="ComboBoxDefault"
          ItemsSource="{Binding DefaultItems, UpdateSourceTrigger=PropertyChanged}" />
    </Grid>
</UserControl>

The CodeBehind of the ComboBox UserControl:

public partial class DefaultComboBox : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
    private ObservableCollection<String> _defaultItems = new ObservableCollection<String>();

    public ObservableCollection<string> DefaultItems
    {
        get { return _defaultItems; }
        set
        {
            _defaultItems = value;
            NotifyPropertyChanged(DefaultItems);
        }
    }

    // Constructor
    public DefaultComboBox()
    {
        UpdateList(ExternalSource.InitialItemList);
        NotifyPropertyChanged("DefaultItems");

        InitializeComponent();
    }

    private void NotifyPropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    // Some DependencProperties like Filter

    // Update Method
    private void UpdateList(List<String> newList)
    {
        DefaultItems = new ObservableCollection<string>(newList);
        NotifyPropertyChanged("DefaultItems");
    }
}

And here is an example of using the Control:

<comboBoxes:DefaultComboBox x:Name="DefaultComboBoxUserView"
                            Filter="{Binding FilterString}"/>

The problem:

If I start my WPF application for the first time and the constructor of DefaultComboBox is called, the UpdateList method works and the ComboBox contains the expected items.

If I use the UpdateList method at runtime, the setter of DefaultItems is called and the items have been correctly updated, but when I click in the GUI on the combo box drop-down, the old items are still there and nothing has been updated.

1

1 Answers

0
votes

You're overriding the value of _defaultItems. That's not what Observable in ObservableCollection does. You should keep the collection instance the same at all times and only Add() and Remove() from it.

One way of entirely replacing the old collection with the new one would be:

// Update Method
private void UpdateList(List<String> newList)
{
    DefaultItems.Clear();
    DefaultItems.AddRange(newItems);
}

Note that this is inefficient and ObservableCollection will update view each time an item is added. There are ways around that, like suspending the notifications until AddRange is done.