简体   繁体   English

如何获取Xamarin Form项目中XAML文件中描述的控件?

[英]How to get controls described in XAML file in a Xamarin Form project?

I can't properly get the control described in XAML file. 我无法正确获取XAML文件中描述的控件。 I gave button in XAML file a ClassId and tried to reach it in CS file using FindByName . 我给XAML文件中的按钮一个ClassId并尝试使用FindByName在CS文件中访问它。

This is in a Xamarin Form project running in iOS Emulator. 这是在iOS模拟器中运行的Xamarin Form项目中。

In MainPage.XAML file, MainPage.XAML文件中,

<StackLayout>
    <!-- Place new controls here -->
    <Button Text="" />
    <Label ClassId="myLabel1"
       Text="Xamarin Form Demo" 
       HorizontalOptions="Center"/>
    <Button ClassId ="btnNum"
       Text="Image Control" 
       HorizontalOptions="Center" />
    <Image ClassId="myImg" 
       HorizontalOptions="Center" />
    <Label ClassId="myLabel2"
       Text="Number" 
       HorizontalOptions="Center"/>
</StackLayout>

In MainPage.xaml.cs file, 在MainPage.xaml.cs文件中,

    public MainPage()
    {
        InitializeComponent();

        int num = 0;
        ((Button)FindByName("btnNum")).Clicked += (o, e) ((Label)FindByName("myLabel2")).Text = (++num).ToString();
    }

When I run the app on iOS Emulator, I always get the following error in the longest line of code in MainPage.xaml.cs file, 当我在iOS Emulator上运行应用程序时,在MainPage.xaml.cs文件中最长的代码行中总是出现以下错误,

********* *********
Unhandled Exception: 未处理的异常:

System.NullReferenceException: Object reference not set to an instance of an object System.NullReferenceException:对象引用未设置为对象的实例

********* *********

Thanks for the help, and it would be nice if I can get some further information about accessing control from a different content page. 感谢您的帮助,如果我可以从其他内容页面获取有关访问控件的更多信息,那将是很好的。

assign your control a Name 为您的控件分配一个名称

<Button x:Name="MyButton" Text="" />

then in the code-behind refer to it by name - you should not need to declare it 然后在后面的代码中按名称引用它-您无需声明它

MyButton.Text = "blah blah blah";

You need to use the x:Name directive, which can be used in any control within Xamarin.Forms. 您需要使用x:Name指令,该指令可以在Xamarin.Forms中的任何控件中使用。

From the docs : 文档

Uniquely identifies XAML-defined elements in a XAML namescope. 在XAML名称范围中唯一标识XAML定义的元素。 XAML namescopes and their uniqueness models can be applied to the instantiated objects, when frameworks provide APIs or implement behaviors that access the XAML-created object graph at run time. 当框架提供API或实现在运行时访问XAML创建的对象图的行为时,可以将XAML名称范围及其唯一性模型应用于实例化的对象。

Usage in XAML: 在XAML中的用法:

<Label x:Name="myLabel1"
       Text="Xamarin Form Demo" 
       HorizontalOptions="Center"/>

<Button 
       x:Name ="btnNum"
       Text="Image Control" 
       HorizontalOptions="Center" />

In Page.xaml.cs 在Page.xaml.cs中

myLabel1.Text = "test";
btnNum.Clicked += 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM