What you are missing is an appropriate view model item class that holds your data. That should not be confused with the view object, e.g. your StockView.
First, remove the ID
and StockName
properties from the StockView control. These properties will move to the data item class.
public partial class StockView : UserControl
{
public StockView()
{
InitializeComponent();
}
}
Second, create the view model with a StockItem
data item class, and a ViewModel
class that has the AllStocks
property (or just call it Test
as you already did).
public class StockItem
{
public string ID { get; set; }
public string StockName { get; set; }
}
public class ViewModel
{
public ObservableCollection<StockItem> AllStocks { get; set; }
}
Finally, set the DataContext of your MainWindow to an instance of the ViewModel class.
public MainWindow()
{
InitializeComponent();
var vm = new ViewModel { AllStocks = new ObservableCollection<StockItem>() };
vm.AllStocks.Add(new StockItem { ID = "M0", StockName = "abc" });
vm.AllStocks.Add(new StockItem { ID = "M1", StockName = "def" });
DataContext = vm;
}
In case the data items could be modified after being added to the AllStocks
collection, the StockItem
class would have to implement the INotifyPropertyChanged
interface.