簡體   English   中英

如何獲取Xamarin Form項目中XAML文件中描述的控件?

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

我無法正確獲取XAML文件中描述的控件。 我給XAML文件中的按鈕一個ClassId並嘗試使用FindByName在CS文件中訪問它。

這是在iOS模擬器中運行的Xamarin Form項目中。

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>

在MainPage.xaml.cs文件中,

    public MainPage()
    {
        InitializeComponent();

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

當我在iOS Emulator上運行應用程序時,在MainPage.xaml.cs文件中最長的代碼行中總是出現以下錯誤,

*********
未處理的異常:

System.NullReferenceException:對象引用未設置為對象的實例

*********

感謝您的幫助,如果我可以從其他內容頁面獲取有關訪問控件的更多信息,那將是很好的。

為您的控件分配一個名稱

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

然后在后面的代碼中按名稱引用它-您無需聲明它

MyButton.Text = "blah blah blah";

您需要使用x:Name指令,該指令可以在Xamarin.Forms中的任何控件中使用。

文檔

在XAML名稱范圍中唯一標識XAML定義的元素。 當框架提供API或實現在運行時訪問XAML創建的對象圖的行為時,可以將XAML名稱范圍及其唯一性模型應用於實例化的對象。

在XAML中的用法:

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

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

在Page.xaml.cs中

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM