获取"名称' SomeName'在当前背景下不存在"在扩展ContentView时

时间:2018-02-27 13:21:41

标签: c# xaml xamarin xamarin.forms

首先,我有一个名为ComponentView的抽象类,继承自ContentView

public abstract class ComponentView : ContentView
{
    private ComponentView() {}

    protected ComponentView(Component component)
    {

    }
}

上面的类由一些自定义可视组件扩展。我首先创建了一个名为SeparatorView的组件。代码背后的XAML结构和C Sharp代码如下:

代码背后:

[XamlCompilation(XamlCompilationOptions.Compile)]
public partial class SeparatorView : ComponentView
{
    private readonly Separator _separator;

    public SeparatorView(Separator separator) : base(separator)
    {
        _separator = separator ?? throw new ArgumentException("Separator cannot be null");

        InitializeComponent();
        RootComponent.AutomationId = _separator.Id;
        Label.Text = _separator.Label;
        HelpBlock.Text = _separator.HelpBlock;
    }
}

XAML文件:

<?xml version="1.0" encoding="utf-8" ?>
<d:ComponentView x:Name="RootComponent" xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:d="clr-namespace:CustomViews.Components"
             x:Class="CustomViews.Components.SeparatorView">
        <StackLayout>
            <Label x:Name="Label"
                VerticalOptions="CenterAndExpand" 
                HorizontalOptions="CenterAndExpand" />
            <Label x:Name="HelpBlock"
                   VerticalOptions="CenterAndExpand" 
                   HorizontalOptions="CenterAndExpand" />
        </StackLayout>
</d:ComponentView>

当我尝试使用此自定义SeparatorView时,我在编译时遇到此错误:

var separator = new Separator
{
    Id = "id",
    Label = "Separator",
    HelpBlock = "Help block"
};
var separatorView = new SeparatorView(separator);
StackLayout.Children.Add(separatorView);
  

SeparatorView.xaml.cs(17,13): [CS0103]名称&#39; RootComponent&#39;不   在当前上下文中不存在

当我删除该行时:

RootComponent.AutomationId = _separator.Id;

代码正常,我的组件正确呈现。

我忘记了什么吗?这与我的班级结构有关吗?

1 个答案:

答案 0 :(得分:4)

您无法命名根元素。事实上,没有必要因为该元素是你已经在里面的类,它实际上是this。所以而不是:

RootComponent.AutomationId = _separator.Id;

这样做:

this.AutomationId = _separator.Id;?