表单:如何在XAML中设置BindingContext?

表单:如何在XAML中设置BindingContext?,xaml,xamarin.forms,Xaml,Xamarin.forms,我有以下一页: <?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=XamForm

我有以下一页:

<?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>

以及背后的代码:

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");
    }
}
public分部类ConnectPage:ContentPage
{
公共ObservableCollection设备列表{get;set;}
公共网页()
{
初始化组件();
DeviceList=新的ObservableCollection();
//BindingContext=这个;
}
public void refreshDeviceList(对象发送方,事件参数e)
{
设备列表。添加(“设备”);
}
}

我试图实现的是将ListView绑定到DeviceList。当我在构造函数中取消对BindingContext行的注释时,它会起作用。我想将该行移到.xaml本身中。研究这个问题会导致.xaml中出现ContentPage.BindingContext块,但这会使程序崩溃。似乎也有在ListView的ItemsSource绑定中设置源代码的方法,但我不理解在我的例子中使用它的语法(我一般不熟悉Xamarin.Forms和XAML)。是否有办法在.xaml中设置BindingContext?

您使用的MVVM是错误的。您正在尝试将viewmodel设置为视图本身。为viewmodel创建一个单独的类,它不应该像您那样从ContentPage派生。

如果您在XAML中设置BindingContext,我想您会生成一个StackOverflowException,因为绑定上下文是ConnectPage,所以该页的许多实例都是递归生成的。尝试拆分这两个概念:您拥有页面,并且必须拥有ViewModel类。ViewModel必须设置为页面的BindingContext。啊。。。那么DataContext是ViewModel吗?现在这是有道理的。谢谢