greyfox
greyfox

Reputation: 6616

WPF Databinding Not Updating UI

I have a XAML and CS file for a UserControl. I have my data stored in a Singleton class which implements INotifyPropertyChanged, and it binds to a ListBox in the UserControl.

This is the XAML databinding:

<ListBox Name="ModsListBox"
    ItemsSource="{Binding ModControls}"
    Visibility="Visible"
    Width="350"
    Height="Auto">
</ListBox>

The datacontext is being set in the CS file as followings:

DataContext = ModDirector.Instance;
InitializeComponent();

In the code there is a method for adding elements which adds the datastructure which is being bound and then calls OnPropertyChanged(), however the UI never updates.

    /// <summary>
    /// Adds a mod and sends event to update UI elements bound to ModContols
    /// </summary>
    /// <param name="modUserControl"></param>
    /// <param name="index"></param>
    public void AddMod(ModUserControl modUserControl, int? index = null)
    {
        if (index != null)
        {
            _modControls.Insert(index.Value, modUserControl);
        }
        else
        {
            _modControls.Add(modUserControl);
        }
        OnPropertyChanged("ModControls");
    }

Just for completion here is the property it is being bound to:

/* Properties */
    public List<ModUserControl> ModControls
    {
        get { return _modControls; }
        set
        {
            _modControls = value;
            OnPropertyChanged();
        }
    }
    /* End Properties */

And the code for OnPropertyChanged

/// <summary>
    /// Fires PropertyChanged event notifying the UI elements bound
    /// </summary>
    /// <param name="propertyName"></param>
    [NotifyPropertyChangedInvocator]
    private void OnPropertyChanged([CallerMemberName] string propertyName = null)
    {
        var handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }

Is there some reason the event would not be propagated?

Upvotes: 0

Views: 459

Answers (2)

Dimitris Michailidis
Dimitris Michailidis

Reputation: 449

Change your List<ModUserControl> to ObservableCollection<ModUserControl>.

Upvotes: 3

nvoigt
nvoigt

Reputation: 77364

Your public List<ModUserControl> ModControls should probably be an ObservableCollection<> instead, so you can remove your manual calls to OnPropertyChanged("ModControls");. Your ModControls did not actually change. It's still the very same instance.

Upvotes: 2

Related Questions