[英]Xamarin Can't Access Controls on Code Behind
對於我的 Xamarin Forms 項目(最新版本 1.3),當我在 Xamarin Studio(最新版本,5.5.4)中創建視圖時,我將視圖定義如下:
<?xml version="1.0" encoding="UTF-8"?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" x:Class="FormsDemo.Register">
<ContentPage.Content>
<Grid>
<Grid.RowDefinitions>
<RowDefinition />
<RowDefinition />
<RowDefinition />
<RowDefinition />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<Label Grid.Row="0" Grid.Column="0" Text="First Name" />
<Entry x:Name="FirstName" Grid.Row="0" Grid.Column="1" />
<Label Grid.Row="1" Grid.Column="0" Text="Last Name" />
<Entry x:Name="LastName" Grid.Row="1" Grid.Column="1" />
<Label Grid.Row="2" Grid.Column="0" Text="Email" />
<Entry x:Name="Email" Grid.Row="2" Grid.Column="1" />
<Button x:Name="SaveButton" Grid.Row="3" Grid.Column="0" Text="Login" />
</Grid>
</ContentPage.Content>
</ContentPage>
但是,在我的代碼隱藏中,根本找不到任何對其名稱的控件的引用。 以下代碼出錯(由注釋指出):
using System;
using System.Collections.Generic;
using Xamarin.Forms;
namespace FormsDemo
{
public partial class Register : ContentPage
{
public Register ()
{
InitializeComponent ();
//Using this approach worked, but is not ideal
this.FindByName<Button>("SaveButton").Clicked += Save_Clicked;
}
void Save_Clicked (object sender, EventArgs e)
{
this.FirstName.Text = "A";
this.LastName.Text= "B";
}
}
}
奇怪的是,我收到了以下警告:
警告:已分配私有字段“FormsDemo.Register.FirstName”,但從未使用其值 (FormsDemo.Solution)
我為每個領域得到一個。 為什么這不起作用? 如何讓 IntelliSense 工作?
最新的更新似乎解決了這個問題; 這些參考工作正常:
this.FirstName.Text = "A";
this.LastName.Text= "B";
看來設計師的一些問題已經解決了。
你可以試試這個
var asdf = this.FindByName<TimePicker>("tagName");
這里有一些建議:
https://forums.xamarin.com/discussion/25409/problem-with-xaml-x-name-and-access-from-code-behind
來自該鏈接的直接回答
在您的頁面屬性上,檢查設置了以下屬性:
BuildAction = 嵌入式資源自定義工具 = MSBuild:UpdateDesignTimeXaml
如果沒問題,請刪除 obj 和 bin 文件夾以重建 PCL。
例如,如果您將 XAML 頁面導入到 PCL 中,則屬性會發生更改並且無法編譯。
我有一個類似的問題,就我而言,這是我自己做的,在 xaml 文件中,我將內容屬性 x:Class 設置為錯誤的值。
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
x:Class="**{namespace.classname}**">
正確指定類名為我解決了這個問題。
在我重命名一些文件並手動更正類引用后,我遇到了同樣的問題。 不知何故,VS 無法從 xaml 頁面找到引用。 當我創建帶有代碼的新 xaml 文件時,相同的代碼可以工作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.