0

I bound a dictionary to a ListView in WPF.

<ListView x:Name="listView" HorizontalAlignment="Left" Height="100" Margin="30,324,0,0" VerticalAlignment="Top" Width="270" ItemsSource="{Binding ArchiveDataDB}">
    <ListView.View>
        <GridView>
             <GridViewColumn Header="Archive Name"
                        DisplayMemberBinding="{Binding Key}" />
             <GridViewColumn Header="Data DB Amount"
                        DisplayMemberBinding="{Binding Value}" />
        </GridView>
    </ListView.View>
</ListView>

Thats my dictionary:

public Dictionary<string, int> ArchiveDataDB
{
    get
    {
        if(_archiveDataDB == null)
        {
            _archiveDataDB = new Dictionary<string, int>();
            _archiveDataDB.Add("Master Data", 0);
        }
        return _archiveDataDB;
    }
    set
    {
        _archiveDataDB = value;
    }
}

I also have a button which should get a string and an int from 2 textboxes and add these 2 information to the list

public void AddEntry(object args)
{
    ArchiveDataDB.Add(ArchiveName, DataDBAmount);
    OnPropertyChanged("ArchiveDataDB");
}

The OnPropertyChanged method gets implemented from the INotifyPropertyChanged interface.

protected void OnPropertyChanged(string name)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(name));
    }
}

For testing purposes i added a MessageBox.Show to the AddEntry method and displayed all entrys. I'm 100% sure that the new key and value gets added to the dictionary, however the ListView does not get updated.

Thanks for your help

Max

Imran Sh
  • 1,623
  • 4
  • 27
  • 50
Maxlisui
  • 69
  • 1
  • 9
  • Did you forget `this.DataContext = this;` in the constructor. – Jeroen van Langen Sep 07 '16 at 12:55
  • Possible duplicate of [Two Way Data Binding With a Dictionary in WPF](http://stackoverflow.com/questions/800130/two-way-data-binding-with-a-dictionary-in-wpf) i would recommend @Ray 's solution – MikeT Sep 07 '16 at 13:30

1 Answers1

1

to quick fix this you can use this:

replace

return _archiveDataDB;

with

return _archiveDataDB.ToDictionary(x=>x.Key, y=>y.Value);

and this line

ArchiveDataDB.Add(ArchiveName, DataDBAmount);

withi this line

_archiveDataDB.Add(ArchiveName, DataDBAmount);

When ListView gets a new instance of dictionary it updates layout.

But to make it properly you should use some implementation od ObservableDictionary or use other observable collection.

For example from here :

.NET ObservableDictionary

I hope that it helps.

Community
  • 1
  • 1
macieqqq
  • 363
  • 2
  • 11