推荐的实现方式是在您的视图模型上拥有一个PageTitle 属性——它与当前的内容视图保持同步;以及相应的标题。
但是,如果您只想在视图级别实现此功能;那么您可以通过在内容视图中引入一个带有绑定模式的自定义可绑定属性作为OneWayToSource 来做到这一点。例如:
public class NavigationView : ContentView
{
public static readonly BindableProperty TitleProperty =
BindableProperty.Create("Title",
typeof(string),
typeof(NavigationView),
defaultValue: null,
defaultBindingMode: BindingMode.OneWayToSource);
public string Title
{
get => (string)GetValue(TitleProperty);
set => SetValue(TitleProperty, value);
}
}
并且,使用自引用将您的自定义属性绑定到 ContentPage 标题。例如:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
....
x:Name="_self"
Title="{Binding Path=Content.Title, Source={x:Reference _self}}">
或者,为自定义视图添加绑定以充分利用绑定模式:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
...
x:Name="_self">
...
<local:NavigationView Title="{Binding Path=Title, Source={x:Reference _self}}">
使用示例
XAML:
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:local="clr-namespace:TitleView"
x:Class="TitleView.TitleViewPage"
x:Name="_self"
Title="{Binding Path=Content.Title, Source={x:Reference _self}}">
<local:NavigationView Title="This is page-1">
<Button Text="Go to page-2" Clicked="Handle_Clicked" />
</local:NavigationView>
</ContentPage>
代码隐藏:
public partial class TitleViewPage : ContentPage
{
void Handle_Clicked(object sender, System.EventArgs e)
{
this.Content = new NavigationView {
Title = "This is page-2",
Content = new Button { Text = "Go back to page-1", IsEnabled = false } };
}
public TitleViewPage()
{
InitializeComponent();
}
}
编辑 1: 还添加了一些代码来说明如何定义从内容视图到页面的绑定。