I am trying to set ItemSource property for listview without success.
View (xaml):
<ListView Margin="10" Name="MyLv" ItemsSource="{Binding}">
....
</ListView>
Code-Behind Constructor (xaml.cs):
public MyView()
{
InitializeComponent();
}
ViewModel:
private List<DataModel> lstData = null;
public MyViewModel()
{
this.lstData = this.LoadData(); // this connects to a database an extract info to be loaded in listview
}
Data Model:
public class DataModel
{
public bool IsSelected { get; set; }
public string ID { get; set; }
public string Desc { get; set; }
}
Before this, I was loading the listview from code-behind and it was working, but now I want to load it from my viewmodel and I do not know how can I make it work.
Based on the code you posted, there are a couple of problems:
You haven't set the DataContext
of the view. You typically want to set this to an instance of your view model class.
The ViewModel
doesn't expose the list as a public property. WPF bindings only work on public properties. The ItemsSource
should be bound to this property, and not to the DataContext
itself.
Finally, you probably want the collection in the ViewModel
to be an ObservableCollection
. This way, when changes are made to the collection, the list in the UI will be automatically updated.