PeteGO
PeteGO

Reputation: 5781

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?

Upvotes: 0

Views: 282

Answers (2)

Matthew Trout
Matthew Trout

Reputation: 741

At first glance, I believe you need to be instantiating the ViewModel and setting its DataContext when you instanciate the view.. Replace the line

var viewModel = new MainViewModel(this.GetStartingPositionChessPieces());

with

this.DataContext = new MainViewModel(this.GetStartingPositionChessPieces());

Because

<Window.DataContext>
<local:MainViewModel />

Will just be using the zero argument constructor and not setting up your pieces).

Please note, DataContext, is not the same as ItemSource.

Hope this helps

Upvotes: 2

Aaron
Aaron

Reputation: 374

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;

Upvotes: 1

Related Questions