[英]Xamarin can't see objects in MainPage.xaml from MainPage.xaml.cs
[英]Unable to see my controls in MainPage.g.cs of my MainPage.xaml
我有一個關於XAML的簡單問題。
我在另一個網格內創建了一個網格元素,並在其中添加了文本塊和Web瀏覽器。 但是,我無法使用其名稱(例如this.LastName)在MainPage.xaml.cs中訪問它。 在進一步調試中,我發現它們未在MainPage.g.cs中聲明。 由於MainPage.g.cs是自動定義的,因此我不知道如何解決它。 有人可以幫忙嗎? 以下是我的C#和XAML代碼。 謝謝! ================================================== ======
public partial class MainPage : Microsoft.Phone.Controls.PhoneApplicationPage {
internal System.Windows.Controls.Grid LayoutRoot;
internal System.Windows.Controls.Grid ContentPanel;
internal Microsoft.Phone.Controls.LongListSelector MainLongListSelector;
internal System.Windows.Controls.Image RefreshIcon;
private bool _contentLoaded;
/// <summary>
/// InitializeComponent
/// </summary>
[System.Diagnostics.DebuggerNonUserCodeAttribute()]
public void InitializeComponent() {
if (_contentLoaded) {
return;
}
_contentLoaded = true;
System.Windows.Application.LoadComponent(this, new System.Uri("/Suod;component/MainPage.xaml", System.UriKind.Relative));
this.LayoutRoot = ((System.Windows.Controls.Grid)(this.FindName("LayoutRoot")));
this.ContentPanel = ((System.Windows.Controls.Grid)(this.FindName("ContentPanel")));
this.MainLongListSelector = ((Microsoft.Phone.Controls.LongListSelector)(this.FindName("MainLongListSelector")));
this.RefreshIcon = ((System.Windows.Controls.Image)(this.FindName("RefreshIcon")));
}
}
================================================== ======
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0">
<phone:LongListSelector x:Name="MainLongListSelector" Margin="-12,-97,0,97" ItemsSource="{Binding Items}">
<phone:LongListSelector.ItemTemplate>
<DataTemplate>
<StackPanel Margin="12,100,0,45">
<Grid x:Name="CompanyContentGrid">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock Grid.Row="0" Name="LastName" Text="{Binding Name}" TextWrapping="Wrap" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
<phone:WebBrowser Grid.Row="5" Height="400" Name="WebBrowser" Margin="12,-6,24,0" FontFamily="Portable User Interface"/>
</Grid>
</StackPanel>
</DataTemplate>
</phone:LongListSelector.ItemTemplate>
</phone:LongListSelector>
</Grid>
<Grid Grid.Row="2" >
<Image Source="/Assets/Refresh.png" Name="RefreshIcon" Width="80" Height="80" Tap="Image_Tap"/>
</Grid>
我認為問題是您的文本塊在xaml代碼中太深了。 我認為在這種情況下數據綁定就足夠了,但是有一種方法可以解決這個問題。 您必須將此元素訂閱某個事件(例如Loaded),並將發件人保存到后面代碼中的某些屬性中:
<TextBlock Loaded="LastName_Loaded" Grid.Row="0" Name="LastName" Text="{Binding Name}" TextWrapping="Wrap" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/>
public TextBlock lastName;
private void LastName_Loaded(object sender, RoutedEventArgs e)
{
lastName= (TextBlock)sender;
}
現在,您可以在后面的代碼中訪問此元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.