batrand
batrand

Reputation: 146

Xamarin.Forms: How to set BindingContext inside XAML?

I have the following page:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:pages="clr-namespace:XamFormsBle.Pages;assembly=XamFormsBle"
         x:Name="ContentPageContainer"
         x:Class="XamFormsBle.Pages.ConnectPage">
  <!--This does not work-->
  <ContentPage.BindingContext>
    <pages:ConnectPage/>
  </ContentPage.BindingContext>

  <StackLayout Orientation="Vertical">
    <Button Text="Refresh"
            Clicked="RefreshDevicesList"/>
    <ListView ItemsSource="{Binding DevicesList}"/>
  </StackLayout>
</ContentPage>

And the code behind:

public partial class ConnectPage : ContentPage
{
    public ObservableCollection<string> DevicesList { get; set; }

    public ConnectPage()
    {
        InitializeComponent();
        DevicesList = new ObservableCollection<string>();
        //BindingContext = this;
    }

    public void RefreshDevicesList(object sender, EventArgs e)
    {
        DevicesList.Add("device");
    }
}

What I am trying to achieve is to bind the ListView to the DevicesList. It works when I uncomment the BindingContext line in the constructor. I want to move that line into the .xaml itself. Researching the matter leads to the ContentPage.BindingContext block in the .xaml, but that crashes the program. There also seems to be the approach of setting the Source inside the binding of the ListView's ItemsSource, but I don't understand the syntax to work it in my case (I'm new to Xamarin.Forms and XAML in general). Is there a way to set the BindingContext inside .xaml?

Upvotes: 2

Views: 4907

Answers (1)

Tolga Kartal
Tolga Kartal

Reputation: 633

You're using MVVM wrong. You're trying to set viewmodel to the view itself. Create a seperate class for the viewmodel, and it shouldn't be deriving from a ContentPage as you did.

Upvotes: 1

Related Questions