random
random

Reputation: 487

Xamarin xaml binding

I am trying to bind my xaml to a property in my view model, but it doesn't work as I expected.

The following code works, but it seems to create a new instance of the mainwindowviewmodel object which will result in problem.

<Label Text="{Binding Path=Test}" >
    <Label.BindingContext>
        <local:MainWindowViewModel />
    </Label.BindingContext>
</Label>

The following doesn't work at all.

<Label Text="{Binding Path=Test}" >
</Label>

I've the property Test in my view model.

What am I doing wrong?

Upvotes: 1

Views: 55

Answers (1)

Nkosi
Nkosi

Reputation: 247018

Make sure to set the BindingContext of the View to an instance of the model (MainWindowViewModel) to make the second code snippet work.

For example in the constructor of the view's code behind

public MainWindow() {
    InitializeComponents();
    var viewModel = new MainWindowViewModel();
    this.BindingContext = viewModel;
}

Or directly in the View

<MainWindow.BindingContext>
    <local:MainWindowViewModel />
</MainWindow.BindingContext>

The both above are technically equivalent.

Upvotes: 1

Related Questions