How to bind a listbox to a list<T> in WPF (MVVM) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

How to bind a listbox to a list<T> in WPF (MVVM)

I have a datamodel with a list<T> In my view I have listbox. I want to bind this list<T> to the listbox. It shows some sort of log and every seconds or so an item is added. I am able to do this, when I load all data at the beginning. But how to make sure that the data is updated every time an item is added. The data is readonly, data is comming from within the application

15th Aug 2019, 8:30 PM
sneeze
sneeze - avatar
8 Answers
+ 1
Use ObservableCollection<t> instead of list<t>
15th Aug 2019, 9:09 PM
Tomasz
Tomasz - avatar
+ 1
Is it correct to use an observableCollection in a datamodel ?
15th Aug 2019, 9:17 PM
sneeze
sneeze - avatar
+ 1
I made some sample code to explain what I want to achieve. https://code.sololearn.com/c02ZH86L4mJ4 The code does compile and runs on my laptop, but the listbox does not show any text (read message). I am really new to MVVM and really confused with all links there need to be there before anything can be displayed. I am aware that in the future there ara advantages, but right now I have trouble to understand how to do it. Tomasz : can you help me ?
18th Aug 2019, 9:08 PM
sneeze
sneeze - avatar
0
Use it inside your viewcontoller.
15th Aug 2019, 9:18 PM
Tomasz
Tomasz - avatar
0
My data is in my model. Should I copy the data from the List<T> to the observablecollection ? Sounds like duplication.
16th Aug 2019, 1:07 PM
sneeze
sneeze - avatar
0
Your data model should always have ICollection or IEnumerable properties for collections, it's nothing wrong to copy data to the observable collection in your viewmodel
16th Aug 2019, 6:27 PM
Tomasz
Tomasz - avatar
0
It looks like you don't know how the MVVM works and how to properly implement it. Your views (Windows) shouldn't contain any logic, the data should be bound instead. I recommend you to read few tutorials, books about the MVVM in WPF. https://www.tutorialspoint.com/mvvm/mvvm_first_application.htm I didn't read this one fully, but it looks like it contains solid basics.
19th Aug 2019, 12:21 PM
Tomasz
Tomasz - avatar
0
Thanks, I am going to have a look at it.
19th Aug 2019, 8:24 PM
sneeze
sneeze - avatar