繁体   English   中英

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

[英]Unable to access and reuse controls from other page

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

预期结果:

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

当前结果:

错误 - Object 引用未设置为 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));
         }
     }
 }

页向日葵.xaml

 <Page [...]>
     <Grid>

     </Grid>
 </Page>

页向日葵.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;
 }

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

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

由于页面上的控件被调用,页面上的控件只有在页面加载完成后才会被实例化。

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

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

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

谢谢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM