无法访问和重用其他页面的控件

Unable to access and reuse controls from other page

我正在尝试使用一个页面来访问不同页面中的某些控件,但出于某种原因,尽管设置了对其他页面的必要引用,它仍然无法正常工作?关于为什么这不起作用以及如何解决这个问题的任何想法?

预期结果:

打开应用 > MainList > 单击列表项 > 转到 PageSunflower > PageSunflower 应该显示 PageTest.xaml 文件的控件

当前结果:

Error - Object reference not set to an instance of an object

MainList.xaml.cs

public sealed partial class MainList : Page
 {
     public List<ListItem> listItemMains;

     public MainList ()
     {
         this.InitializeComponent();

         listItemMains = ItemManagerMains.GetListItems();
     }

     private void ListMain_ItemClick(object sender, ItemClickEventArgs e)
     {
         ListItemMain item = (ListItemMain)e.ClickedItem;

         if (item.FlowerName == "Sunflower")
         {
             Frame.Navigate(typeof(PageSunflower));
         }
         else
         {
             Frame.Navigate(typeof(PageDaffodil));
         }
     }
 }

PageSunflower.xaml

 <Page [...]>
     <Grid>

     </Grid>
 </Page>

PageSunflower.xaml.cs

 public sealed partial class PageSunflower : Page
 {
     public PageSunflower()
     {
         this.InitializeComponent();

         TabView tabview = PageTest.Current.MyTabs;

         TextBlock txtTitle = PageTest.Current.txtPageTitle;
         txtTitle.Text = "hello";
     }
 }

PageTest.xaml

 <Page [...]>
     <Grid>
         <Grid.RowDefinitions>
             <RowDefinition Height="Auto"/>
             <RowDefinition Height="*"/>
         </Grid.RowDefinitions>
         <StackPanel Grid.Row="0">
             <TextBlock x:Name="txtTitle" x:FieldModifier="public"/>

         <controls:TabView x:FieldModifier="public" Grid.Row="1" x:Name="MyTabs"/>
     </Grid>
 </Page>

PageTest.xaml.cs

 public sealed partial class PageTest : Page
 {
     public PageTest()
     {
         this.InitializeComponent();

         Current = this;
     }

     public static PageTest Current;
 }

如果想通过静态变量获取其他页面的控制权,需要两个条件:

  1. 此页面已加载。
  2. 页面已缓存。

由于调用了页面上的控件,因此只有在页面加载后才会实例化页面上的控件。

另外,当页面不是当前Frame的内容时,页面可能会被卸载,此时会释放引用,无法获取控件,所以页面应该被缓存。

所以如果你想获取页面中的控件,请确保页面已经加载(即一旦导航到页面),然后缓存页面,像这样:

public PageTest()
{
    this.InitializeComponent();
    NavigationCacheMode = NavigationCacheMode.Enabled;
    Current = this;
}

谢谢。