简体   繁体   中英

How to access Title property on ContentPage from a subclass in Xamarin Forms?

I have the following code in XAML:

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    xmlns:local="clr-namespace:AAA;assembly=AAA"
    x:Class="AAA.FavoritesPage">
   <ContentPage.Content>
      <StackLayout BackgroundColor="{Binding ThemeBackgroundColor}" HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand">
         <local:FavoritesFrameRendererSubClass/>
      </StackLayout>
   </ContentPage.Content>
</ContentPage>

I want to be able to change the ContentPage 's Title property in the OnBindingContextChanged of my subclass C# code like below:

public partial class FavoritesFrameRendererSubClass : Frame
{
   protected override void OnBindingContextChanged()
   {
      // Dynamically change the ContentPage's title here
      Title = App.index + " of " + App.favoriteWords.Count;
   }
}

Anyone have any idea if this is possible? If so, how?

While the accepted answer works, it is a fairly heavy approach. Instead of a public static exposing the entire item, when faced with this issue, casting and walking though the Parent property can get access to the Title property.

For example, let's say you have a ContentPage that is reused and each instance must dynamically change its Title. This use-case utilizes the Shell and sets the Title for the ContentPage to the Title of the ShellContent shown when the flyout appears.

((TemplatedPage)this).Title = ((BaseShellItem)((TemplatedPage)this).Parent).Title;

If faced with a deeper hierarchy, use the debugger to figure out the necessary casting and walk through the Parent properties to get to the Title desired.

You need to declare a Static object of ContentPage publically.

public static FavoritesPage FavoritesPageCS;
public FavoritesPage()
{
   FavoritesPageCS = this;
}

and from your child page or any other, you can access the Title with FavoritesPage.Title

Hope this will work for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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