Search code examples
wpfbindingitemsource

WPF ItemSource Not Working in XAML


I am writing a chess UI in WPF.

I have set the window datacontext in XAML:

<Window.DataContext>
    <local:MainViewModel />
</Window.DataContext>

I've defined the 'local' namespace as the namespace which holds the view model.

xmlns:local="clr-namespace:ChessUI"

The view model has 1 property, a collection of chess pieces:

public class MainViewModel
{
    public ObservableCollection<ChessPiece> ChessPieces { get; set; }

    public MainViewModel()
        :this(new ObservableCollection<ChessPiece>())
    {
    }

    public MainViewModel(IEnumerable<ChessPiece> chessPieces)
    {
        this.ChessPieces = new ObservableCollection<ChessPiece>(chessPieces);
    }
}

I've tried to bind the ChessPieces to my ChessBoard (an ItemsControl) like this:

<Viewbox RenderOptions.BitmapScalingMode="HighQuality">
    <ItemsControl Name="ChessBoard" ItemsSource="{Binding ChessPieces}">
        [...]
    </ItemsControl>
</Viewbox>

But it doesn't show the pieces at runtime. However, if I uncomment the line below it works and I see all the pieces on the board.

public MainWindow()
{
    InitializeComponent();
    var viewModel = new MainViewModel(this.GetStartingPositionChessPieces());
    //this.ChessBoard.ItemsSource = viewModel.ChessPieces;
}

Just to be clear:

With the binding set in the XAML:

No Pieces!

With the binding set in the code:

With pieces!

Anyone know what I'm doing wrong with the XAML binding?


Solution

  • In your code example,

    public MainWindow()
    {
        InitializeComponent();
        var viewModel = new MainViewModel(this.GetStartingPositionChessPieces());
        //this.ChessBoard.ItemsSource = viewModel.ChessPieces;
    }
    

    You are creating a viewModel but not using it. Perhaps if you assigned it as the window's DataContext:

    this.DataContext = viewModel;