【发布时间】:2015-09-28 02:03:47
【问题描述】:
将代码添加到登录页面及其 ViewModel 后,我收到以下错误:
在类型“Xamarin.Forms.View”中找不到方法 FindByName
和
无法解析类型:Content.FindByName
这是导致它的代码:
protected override void OnAppearing()
{
base.OnAppearing();
string platformName = Device.OS.ToString();
//THESE NEXT TWO LINES IS WHERE THE **REAL** PROBLEM OCCURS
Content.FindByName<Button>("loginButton" + platformName).Clicked += OnLoginClicked;
Content.FindByName<Button>("helpButton" + platformName).Clicked += OnHelpClicked;
}
这是页面内容:
<ContentPage.Content>
<OnPlatform x:TypeArguments="View">
<OnPlatform.iOS>
<StackLayout VerticalOptions="StartAndExpand"
Padding="30">
<Image Source="logo" />
<Entry StyleId="UserId"
Text="{Binding Path=Username}"
Placeholder="Username" />
<Entry StyleId="PasswordId"
Text="{Binding Path=Password}"
Placeholder="Password"
IsPassword="true" />
<Grid HorizontalOptions="Center">
<Button x:Name="loginButtoniOS"
Text="Login"
Grid.Row="0"
Grid.Column="0"
Style="{StaticResource ButtonStyle}" />
<Button x:Name="helpButtoniOS"
Text="Help"
Grid.Row="0"
Grid.Column="1"
Style="{StaticResource ButtonStyle}" />
</Grid>
</StackLayout>
</OnPlatform.iOS>
这段代码以前可以工作,唯一的变化是LoginPageViewModel,添加了一个登录方法:
public async Task<bool> Login()
{
...
知道Content.FindByName<Button> 方法失败的原因吗?
这显然会导致应用程序崩溃,因为当它为空时分配给Clicked 事件。所以我看到的错误是:
System.NullReferenceException:对象引用未设置为对象的实例
我将它调试回这些调用:
Content.FindByName<Button>("loginButton" + platformName).Clicked += OnLoginClicked;
Content.FindByName<Button>("helpButton" + platformName).Clicked += OnHelpClicked;
这似乎可以工作,因为当我越界时它们会默默地失败,但我 99% 确定它们是问题:
【问题讨论】:
-
谢谢。我正在做 this.findByName 而不是 Content.findByName 这有助于我跟踪它。
标签: c# methods xamarin xamarin.forms