【问题标题】:Xamarin Error: Can not find the object referenced byXamarin 错误:找不到所引用的对象
【发布时间】:2020-10-10 13:29:06
【问题描述】:

我在使用 Xamarin 数据绑定时遇到了一点问题。绑定到 C# 类中的项目时,我收到标题中的错误。我一直在尝试从找到here 的表示例中绑定一个元素。我尝试将BindingContext = this; 添加到构造函数中,并将类声明上方的行更改为[DesignTimeVisible(false)],就像在创建项目期间找到的主从模板中的NewItemPage 一样,但是,它没有帮助。

代码如下:

XAML:

<?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:d="http://xamarin.com/schemas/2014/forms/design"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             mc:Ignorable="d"
             x:Class="NetworkScanner.Views.TestPage">
    <TableView>
        <TableRoot>
            <TableSection Title="Getting Started" BindingContext="{x:Reference Table}">
                <ViewCell>
                    <StackLayout Orientation="Horizontal">
                        <Image Source="bulb.png" />
                        <Label Text="left"
                                 TextColor="#f35e20" />
                        <Label Text="right"
                                 HorizontalOptions="EndAndExpand"
                                 TextColor="#503026" />
                    </StackLayout>
                </ViewCell>
            </TableSection>
        </TableRoot>
    </TableView>
</ContentPage>

C#:

使用系统;
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
使用 System.Threading.Tasks;

使用 Xamarin.Forms;
使用 Xamarin.Forms.Xaml;

命名空间 NetworkScanner.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    // [DesignTimeVisible(false)]
    公共部分类 TestPage : ContentPage
    {
        公共 TableSection 表 { 获取;放; }
        公共测试页()
        {
            初始化组件();
            // BindingContext = this;
        }
    }
}

【问题讨论】:

  • 你想完成什么?您正在设置 BindingContext,但没有任何绑定表达式,并且您从未初始化您的 Table 属性。一般来说,如果你想要一个数据驱动的表,你会使用 ListView 或 CollectionVIew,而不是 TableView。

标签: c# xaml xamarin xamarin.forms


【解决方案1】:

您必须使用关键字 Binding 而不是 x:Reference。

<TableSection Title="Getting Started" BindingContext="{Binding Table}">

【讨论】:

  • 它不会再导致构建错误,但Table的值仍然为空。
  • 它为空,因为您必须创建 TableSection 的实例。
  • 在构造函数中创建实例,如“Table = new TableSection();”或者,如果您不想创建它,请将 x:Name 属性赋予 XAML 或 cs 文件中的 TableSection ,将此名称赋予 Table 属性。 XAML 表中的 = section;在后端。
猜你喜欢
  • 1970-01-01
  • 2015-06-02
  • 1970-01-01
  • 2019-11-27
  • 2013-12-07
  • 2017-09-28
  • 2018-06-06
  • 2020-01-25
  • 1970-01-01
相关资源
最近更新 更多