0

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.

Jaeriko
  • 31
  • 10
  • WPF data binding works with public properties only. Change the dclaration to `public ObservableCollection colors { get; } = ...` – Clemens Apr 20 '18 at 06:53
  • @Clemens Yeah, that did it. A bit embarrassing but thank you. Would you like to make this a post so I can mark it correct when it lets me? – Jaeriko Apr 20 '18 at 06:55
  • That's odd, because I searched for similar cases for nearly 40 minutes before making this post. Perhaps the question board would benefit from a less specifically worded question that people are more likely to find when they're using fields instead of properties? – Jaeriko Apr 20 '18 at 07:00

0 Answers0