gpt4 book ai didi

c# - 扩展 ContentView 时获取 "The name ' SomeName' does not exist in the current context"

转载 作者:太空狗 更新时间:2023-10-30 01:13:38 25 4
gpt4 key购买 nike

首先,我有一个名为 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] The name 'RootComponent' does not exist in the current context

当我删除该行时:

RootComponent.AutomationId = _separator.Id;

代码有效,我的组件已正确呈现。

我是不是忘记了什么?这与我的类(class)结构有关吗?

最佳答案

您不能命名根元素。事实上,没有必要,因为该元素是您已经在其中的类,它实际上是 this。所以不是:

RootComponent.AutomationId = _separator.Id;

只需这样做:

this.AutomationId = _separator.Id;? 

关于c# - 扩展 ContentView 时获取 "The name ' SomeName' does not exist in the current context",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49009708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com