简体   繁体   中英

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

I can't properly get the control described in XAML file. I gave button in XAML file a ClassId and tried to reach it in CS file using FindByName .

This is in a Xamarin Form project running in iOS Emulator.

In MainPage.XAML file,

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

    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,

*********
Unhandled Exception:

System.NullReferenceException: Object reference not set to an instance of an object

*********

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.

From the docs :

Uniquely identifies XAML-defined elements in a XAML namescope. 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.

Usage in XAML:

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

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

In Page.xaml.cs

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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