2
votes

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?

1
If you set the BindingContext inside the XAML, I suppose that you generate a StackOverflowException, because the binding context is the ConnectPage, so many instances of this page are generated recursively. Try to split these two concepts: you have the page, and you must have a ViewModel class. The ViewModel must be set as BindingContext of the Page. - Igor Damiani

1 Answers

1
votes

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.