I'm trying to set the ItemSource of a ListBox to bind to a collection within a viewmodel, but it won't work unless I make my DataContext directly equal to that collection (ex. DataContext= vm.colorList
) rather than to just the vm.
Essentially, I have a ViewModel that looks like this:
public class MosaicBoard
{
public ObservableCollection<Rectangle> colors = new ObservableCollection<Rectangle>();
public List<string> testList = new List<string>();
public ObservableCollection<MosaicCellItem> boardSquares = new ObservableCollection<MosaicCellItem>();
public MosaicBoard()
{
for (int i = 0; i < 50; i++)
{
for (int j = 0; j < 50; j++)
{
boardSquares.Add(new MosaicCellItem() {Col = j, Row=i});
}
}
colors.Add(new Rectangle() { Width = 90, Height = 90, StrokeThickness = 1, Fill = new SolidColorBrush(Colors.Blue) });
testList.Add("test1");
}
}
A View using it that looks like this:
public partial class MainWindow : Window
{
private Point startPoint;
public MosaicBoard vm = new MosaicBoard();
public MainWindow()
{
InitializeComponent();
this.DataContext = vm;
}
}
and XAML that looks like this:
<ListBox x:Name="listbox" ItemsSource="{Binding colors}" />
As I understand it, this should be working by referencing the collection within the viewmodel. To make it work, I have to make DataContext = vm.colors
, and ItemsSource="{Binding}"
, but this seems wrong and prevents me from using the other collection in the vm.
I'd really like to know why my {Binding colors} doesn't work in this context.