首页 > 解决方案 > 导航后如何更改页面标题

问题描述

我已经为 FirstPage 使用设置了一个标题App._variable = "Title",在Navigation.PushAsync(new SecoundPage())我设置App._variable = "New Title"之后然后Navigation.PopAsync())返回到 FirstPage,当我导航回到 FirstPage 时,标题仍然是“标题”,我该如何更改?

编辑 App.xaml.cs

namespace Test
{
    public partial class App : Application
        {
        public static int _ItemId { get; set; }

        public App()
        {
        InitializeComponent();

        MainPage = new NavigationPage(new FirstPage());
        }
    }
}

第一页.xaml.cs

private async void BtnSecoundPage_Clicked(object sender, EventArgs e)
{
    await Navigation.PushAsync(new SecoundPage());
}

SecoundPage.xaml.cs(有一个 ListView)

private void LVCustomerList_ItemSelected(object sender, SelectedItemChangedEventArgs e)
{
    var selectedItem = e.SelectedItem as Items; //Item Model

    App._ItemId = selectedItem.ID;
    Navigation.PopAsync();
}

标签: c#xamarinxamarin.forms

解决方案


您需要正确设置绑定。

在您的 XAML 中,确保为您的标题设置绑定...

<?xml version="1.0" encoding="UTF-8"?>
<ContentPage 
    xmlns="http://xamarin.com/schemas/2014/forms" 
    xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
    x:Class="PlaypenApp.TestPage"
    Title="{Binding Title}">

</ContentPage>

...然后在您的代码隐藏中(如果这是您正在使用的),您需要确保为页面设置绑定上下文...

this.BindingContext = this;

...将上面的代码行放在对 InitializeComponent() 的调用之前

现在向您的页面添加一个属性,这将取代您对 App._variable 的使用...

private string _title;
public string Title
{
    get { return _title; }
    set { _title = value; OnPropertyChanged(); }
}

...然后要全面测试,请使用此代码(其中包含我在上面指定的一些代码)...

public TestPage()
{
    this.BindingContext = this;

    Title = "Old Title";

    InitializeComponent();

    Device.BeginInvokeOnMainThread(async () =>
    {
        await Task.Delay(2000);

        Title = "New Title";
    });
}

2 秒后,页面上的标题应该会改变。

我希望这对你有用。让我知道你怎么去。


推荐阅读